
// History Listing
#include "clog.h"
#include "cgi.h"
#include "input.h"
#include "wrenchboard_api.h"
#include "history.h"
#include "media.h"
#include "email.h"
#include "payments.h"
#include "safestring.h"
#include <string>
#include "pgsql.h"
#include "pgsql_wrapper.h"
#include "cfg.h"
#include <curl/curl.h>

/*
CREATE TABLE members_myfiles (
	id SERIAL,
	member_id INT REFERENCES members(id) NOT NULL,
	uid  uuid  DEFAULT uuid_generate_v4(),
	file_name VARCHAR(35),
	saved_file_name VARCHAR(35) UNIQUE NOT NULL,
	file_size INT DEFAULT 0,
	file_type VARCHAR(15),
	title VARCHAR(35),
	description VARCHAR(100),
	status INT DEFAULT 1,
    added timestamp without time zone DEFAULT now(),
    updated timestamp without time zone DEFAULT now()
	);
 ALTER TABLE ONLY members_myfiles
    ADD CONSTRAINT members_myfiles_id_key UNIQUE (id);

                $data = [
                    'action' => WRENCHBOARD_GET_MEDIA,
                    'sessionid' => $sessionId,
                    'file_section' => $fileSection,
                    'file_uid' => $fileUID,
                ];


*/



long WrenchFindStoredMedia(CVars in, CVars &out) {
    logfmt(logINFO, "WrenchFindStoredMedia()");
    long ret = PHP_API_BAD_PARAM;
    char vname[700];
    char file_section[50];
    try {
        REQ_STRING(in, "sessionid", 3, 150, "(.*)");
        REQ_STRING(in, "file_uid", 3, 150, "(.*)");
        long file_section_no = REQ_LONG( in, "file_section", 1, -1 );
        snprintf(file_section, sizeof (file_section), "%s", in["file_section"].c_str());

      switch(file_section_no){

                case WRENCH_FILE_PROFILE:
                //file_uid  is the UID of the user
                  snprintf(vname, sizeof (vname), "SELECT uid AS member_uid, profile_pic AS saved_file_name FROM members WHERE uid ='%s'", in["file_uid"].c_str());
                break;

                case WRENCH_FILE_FAMILYBANNER:
                  snprintf(vname, sizeof (vname), "SELECT uid AS member_uid, fam_banner AS saved_file_name FROM members WHERE uid ='%s'", in["file_uid"].c_str());
                break;

                case WRENCH_FILE_MYFILE:
                    snprintf(vname, sizeof (vname), "SELECT m.uid AS member_uid, mm.uid AS flie_uid, mm.* "
                                                     " FROM members_myfiles mm LEFT JOIN members m ON m.id=mm.member_id "
                                                     " WHERE mm.uid ='%s'", in["file_uid"].c_str());
                break;

                case WRENCH_FILE_CONTRACTS:
                /*

wrenchboard=> select * from jobs_contract_message where msg_type ='FILE' limit 1;
 id | member_id |    contract    | msg_type |        message         | status |          created           |                 uid
----+-----------+----------------+----------+------------------------+--------+----------------------------+--------------------------------------
  5 |         1 | ABCDEFG0IJK002 | FILE     | delivery-zip-files.zip |      1 | 2017-03-14 00:11:37.881015 | 7d347a17-9d4e-4067-a7a2-ba05c116626f
(1 row)

                */
                    snprintf(vname, sizeof (vname), "SELECT message AS saved_file_name, contract "
                                                    " FROM jobs_contract_message WHERE uid = '%s'", in["file_uid"].c_str());
                break;

                case WRENCH_FILE_FAMILY:
//                    snprintf(vname, sizeof (vname), "SELECT uid AS member_uid, profile_pic AS saved_file_name, '%s' AS family_uid "
//                                                    " FROM members WHERE id = (SELECT family_member_id FROM members_family WHERE uid = '%s')", in["file_uid"].c_str(), in["file_uid"].c_str());

                   snprintf(vname, sizeof (vname), "SELECT f.uid AS family_uid,m.profile_pic AS saved_file_name, f.family_member_id, mm.uid AS member_uid "
                                                    " FROM members_family f "
                                                    " LEFT JOIN members mm ON mm.id = f.member_id  "
                                                    " LEFT JOIN members m ON m.id = f.family_member_id  "
                                                    " WHERE  f.uid='%s' ", in["file_uid"].c_str() );

                break;

                case WRENCH_FILE_JOB:  // primary picture only
                      snprintf(vname, sizeof (vname), "SELECT *,pic1 AS saved_file_name FROM members_jobs_pictures WHERE job_uid='%s' ", in["file_uid"].c_str());
                    break;

                case WRENCH_FILE_JOBFILE:
                     snprintf(vname, sizeof (vname), "SELECT * , filename AS saved_file_name FROM members_jobs_files WHERE uid='%s' ", in["file_uid"].c_str());
                    break;
      }

        if ( load_db_record(out, "%s", vname) > 0){
            ret = PHP_API_OK;
        }

    } catch (bad_parameter) {
        logfmt(logINFO, "ERROR CALL long WrenchFindStoredMedia(CVars in, CVars &out)");
    }
    logfmt(logINFO, "/WrenchFindStoredMedia()");
    return ret;
}


long WrenchSaveStoredMedia(CVars in, CVars &out) {
    logfmt(logINFO, "WrenchSaveStoredMedia()");
    long ret = PHP_API_BAD_PARAM;
    char vname[500];
    char file_section[50];
    CVars fm;
    CVars xx;
    CVars yy;
    long job_pic_id = 0 ;

    bzero(vname, sizeof (vname));
    bzero(file_section, sizeof (file_section));

    try {
       // REQ_STRING(in, "file_section", 5, 40, "(.*)");

        long file_section_no = REQ_LONG( in, "file_section", 1, -1 );
        REQ_STRING(in, "sessionid", 3, 150, "(.*)");
        //snprintf(file_section, sizeof (file_section), "%s", in["file_section"].c_str());

      switch(file_section_no){

                case WRENCH_FILE_PROFILE:
                    REQ_STRING(in, "uid", 3, 150, "(.*)");
                    REQ_STRING(in, "profile", 5, 40, "(.*)");
                    pgsql_exec("UPDATE members SET profile_pic='%s' "
                             " WHERE uid='%s'",in["profile"].c_str(), in["uid"].c_str());
                              out["save_status"] ="completed";
                    snprintf(vname, sizeof (vname), "SELECT * FROM members WHERE uid ='%s'", in["uid"].c_str());
                break;

                case WRENCH_FILE_FAMILYBANNER:
                    REQ_STRING(in, "uid", 3, 150, "(.*)");
                    REQ_STRING(in, "profile", 5, 40, "(.*)");
                    pgsql_exec("UPDATE members SET fam_banner='%s' "
                             " WHERE uid='%s'",in["profile"].c_str(), in["uid"].c_str());
                              out["save_status"] ="completed";
                    snprintf(vname, sizeof (vname), "SELECT * FROM members WHERE uid ='%s'", in["uid"].c_str());
                break;

                case WRENCH_FILE_MYFILE:
//                    snprintf(vname, sizeof (vname), "SELECT m.uid AS member_uid, mm.uid AS flie_uid, mm.* "
//                                                     " FROM members_myfiles mm LEFT JOIN members m ON m.id=mm.member_id "
//                                                     " WHERE mm.uid ='%s'", in["file_uid"].c_str());
                   snprintf(vname, sizeof (vname), "SELECT * FROM members WHERE id =1");
                break;

                case WRENCH_FILE_CONTRACTS:
                   // snprintf(vname, sizeof (vname), "SELECT * FROM members WHERE id =1", in["file_uid"].c_str());
                   snprintf(vname, sizeof (vname), "SELECT * FROM members WHERE id =1");
                break;

                case WRENCH_FILE_FAMILY:
                    REQ_STRING(in, "uid", 3, 150, "(.*)");
                    REQ_STRING(in, "family_uid", 5, 150, "(.*)");

                    if (load_db_record(fm, "SELECT f.uid, f.family_member_id, mm.uid FROM members_family f "
                                           " LEFT JOIN members mm ON mm.id = f.member_id  "
                                           " WHERE mm.uid ='%s' AND f.uid='%s' ", in["uid"].c_str(), in["family_uid"].c_str()) > 0){

                                if ( fm["family_member_id"].Long() > 0){
                                    pgsql_exec("UPDATE members SET profile_pic='%s' "
                                    " WHERE id=%lu",in["profile"].c_str(), fm["family_member_id"].Long());
                                    out["save_status"] ="completed";
                                    snprintf(vname, sizeof (vname), "SELECT * FROM members WHERE id =%lu ",  fm["family_member_id"].Long());
                                }
                                else{
                                  out["error"] ="account_not_found";
                                }
                     }
                break;

                case WRENCH_FILE_JOB:  // primary picture only
                    REQ_STRING(in, "uid", 3, 150, "(.*)");
                    REQ_STRING(in, "job_uid", 5, 150, "(.*)");
                    REQ_STRING(in, "profile", 5, 40, "(.*)");

                    if (load_db_record(fm,"SELECT j.id, j.uid,m.uid,m.id AS member_id FROM members_jobs j "
                                          " LEFT JOIN members m ON m.id = j.member_id "
                                          " WHERE m.uid = '%s' AND j.uid='%s' ", in["uid"].c_str(), in["job_uid"].c_str()) > 0){
                                          // We are sure you own this job
                                          if ( load_db_record(xx,"SELECT id, uid FROM members_jobs_pictures WHERE job_uid='%s' ",in["job_uid"].c_str()) > 0){
                                                job_pic_id= xx["id"].Long();
                                                yy["pic1"] = in["profile"]; yy["pic1"].set_valid( true );
                                                update_db_record(DBS_VALID, "members_jobs_pictures", yy, job_pic_id) ;
                                          }
                                          else
                                          {
                                             yy["pic1"] = in["profile"]; yy["pic1"].set_valid( true );
                                             yy["job_uid"] = in["job_uid"]; yy["pic1"].set_valid( true );
                                             yy["member_id"] = fm["member_id"]; yy["member_id"].set_valid( true );
                                             yy["member_uid"] = in["uid"]; yy["member_uid"].set_valid( true );
                                             job_pic_id = insert_db_record(DBS_VALID, "members_jobs_pictures", "members_jobs_pictures_id_seq", yy);
                                          }
                                       }else{
                                          out["error"] ="job_not_found";
                                       }

                break;

      }

        if ( load_db_record(out, "%s", vname) > 0){
            ret = PHP_API_OK;
        }

    } catch (bad_parameter) {
        logfmt(logINFO, "ERROR CALL long WrenchSaveStoredMedia(CVars in, CVars &out)");
    }
    logfmt(logINFO, "/WrenchSaveStoredMedia()");
    return ret;
}
//ALTER TABLE members_family ADD profile_pic VARCHAR(35);

