import { Meteor } from 'meteor/meteor';
import { check } from 'meteor/check';
import { HTTP } from 'meteor/http';

let uuidv4 = require("uuid/v4");

// Accounts.onLogin(function(user) {
//    
//     console.log(",", user.user._id)
// });

import Worklist from '../collections/worklist.js';
import InternalWorklist from '../collections/internalworklist.js';

let internalWorklistName = 'InternalHis';

// import workListItemSchema from '../collections/worklistItemSchema.js';


import { Logger } from 'meteor/ostrio:logger';
import { LoggerFile } from 'meteor/ostrio:loggerfile';

var log = new Logger();
(new LoggerFile(log)).enable();

Meteor.methods({
    'Fetchworklist' (devicemap) {

        this.unblock();
        if (this.userId) {
            Meteor.settings.enableDebug ? log.debug(`Fetchworklist() => start Fetchworklist `, devicemap, Meteor.user().username) : '';
            check(devicemap, String);
            if (devicemap.length == 0) {
                Meteor.settings.enableDebug ? log.debug(`Fetchworklist() => devicemap is empty `, devicemap, Meteor.user().username) : '';
                return true;
            }
            try {
                Meteor.settings.enableDebug ? log.debug(`Fetchworklist() => start get worklist from restapi `, devicemap, Meteor.user().username) : '';
                const result = HTTP.call('GET', `${Meteor.settings.worklistUrl}/HISIntegration.svc/rest/Fetchworklist/${devicemap}`);
                Meteor.settings.enableDebug ? log.debug(`Fetchworklist() => worklist have been fetched from restapi `, result, Meteor.user().username) : '';

                let worklistHttp = JSON.parse(result.content);

                Meteor.settings.enableDebug ? log.debug(`Fetchworklist() => start remove worklist for user and devicemap `, devicemap, Meteor.user().username) : '';
                Worklist.remove({ _userid: this.userId, _devicemap: devicemap });
                Meteor.settings.enableDebug ? log.debug(`Fetchworklist() => worklist for user and devicemap have been removed`, devicemap, Meteor.user().username) : '';

                Meteor.settings.enableDebug ? log.debug(`Fetchworklist() => start inserting worklist for user and devicemap into tempcollection `, devicemap, Meteor.user().username) : '';
                worklistHttp.WorkListItems.forEach((patient) => {
                    delete patient._id;
                    Worklist.insert({
                        ...patient,
                        _userid: this.userId,
                        _devicemap: devicemap
                    });
                });

                Meteor.settings.enableDebug ? log.debug(`Fetchworklist() => worklist for user and devicemap have been inserted into tempcollection `, devicemap, Meteor.user().username) : '';

                return true
            } catch (e) {
                log.error(`Fetchworklist() => error fetching worklist`, e, Meteor.user().username);
                throw new Meteor.Error("error");
            }
        }
    },
    "EditworklistItem" (item) {

        // const item = {
        //     "Accession": "",
        //     "AdmissionID": "1501",
        //     "EnglishFirstName": "SHOOSHAN",
        //     "EnglishFirstNameParts": [
        //         "SHOOSHAN"
        //     ],
        //     "EnglishLastName": "????? KHAZER ABADI",
        //     "EnglishLastNameParts": [
        //         "KHASHILO",
        //         "KHAZER",
        //         "ABADI"
        //     ],
        //     "FarsiFirstName": "شوشان",
        //     "FarsiFirstNameParts": [
        //         "شوشان"
        //     ],
        //     "FarsiLastName": "خشيلو خزر ابادي",
        //     "FarsiLastNameParts": [
        //         "خشيلو",
        //         "خزر",
        //         "ابادي"
        //     ],
        //     "FarsiName": "شوشان^خشيلو خزر ابادي",
        //     "HISID": null,
        //     "InstitutionAddress": null,
        //     "InstitutionName": null,
        //     "Modality": "",
        //     "PPSStatus": 0,
        //     "PatientAge": "67",
        //     "PatientBirthDate": "1990/01/01",
        //     "PatientID": "132748",
        //     "PatientWeight": 0,
        //     "PatinetSex": "0",
        //     "PatinetSize": 0,
        //     "PregnancyStatus": 4,
        //     "ProcedureID": null,
        //     "ProcedureSteps": [],
        //     "ReferringPhysicianName": null,
        //     "RequestedProcedureID": "1501",
        //     "ScheduledStartDate": null,
        //     "Smoking": 2,
        //     "StudyInstanceUID": "1.3.12.2.1107.5.2.30.26719.6.8122118808"
        // }
        try {

            if (this.userId) {
                delete item._id;
                // workListItemSchema.validate(item);
                Meteor.settings.enableDebug ? log.debug(`EditworklistItem() => start EditWorklist `, item, Meteor.user().username) : '';
                var options = {
                    data: item,
                    headers: {
                        'content-type': 'application/json',
                        'Accept': 'application/json'
                    }
                }
                Meteor.settings.enableDebug ? log.debug(`EditworklistItem() => start calling editworklist restapi `, {}, Meteor.user().username) : '';
                const result = HTTP.call('POST', `${Meteor.settings.worklistUrl}/HISIntegration.svc/rest/EditworklistItem`, options);
                Meteor.settings.enableDebug ? log.debug(`EditworklistItem() => editworklist restapi have been called `, result, Meteor.user().username) : '';
                let result1 = JSON.parse(result.content);
                delete result1._id;
                Meteor.settings.enableDebug ? log.debug(`EditworklistItem() => start updating temp collection for edited item in worklist `, result1, Meteor.user().username) : '';
                let update = Worklist.update({ AdmissionID: result1.AdmissionID }, { $set: result1 }, { multi: true });
                Meteor.settings.enableDebug ? log.debug(`EditworklistItem() => updating temp collection for edited item in worklist have been done`, update, Meteor.user().username) : '';
                return true;
            }
        } catch (e) {
            log.error(`EditworklistItem() => error editing worklist`, e, Meteor.user().username);
            throw new Meteor.Error("error");
        }
    },
    "Register" (item) {
        try {
            if (this.userId) {
                Meteor.settings.enableDebug ? log.debug(`Register() => start Register patient into internalworklist `, item, Meteor.user().username) : '';
                item._id = uuidv4();
                item.PatientDate = new Date();

                InternalWorklist.insert({
                    ...item
                });
                Meteor.settings.enableDebug ? log.debug(`Register() => patient inserted into internalworklist `, {}, Meteor.user().username) : '';


                // Worklist.remove({ _userid: this.userId, _devicemap: internalWorklistName });

                // Worklist.insert({
                //     ...item,
                //     _userid: this.userId,
                //     _devicemap: internalWorklistName
                // });
                return true;
            }
        } catch (e) {
            log.error(`EditworklistItem() => error editing worklist`, e, Meteor.user().username);
            throw new Meteor.Error("error");
        }

    }
});