import { Injectable } from '@angular/core';
import { Platform } from '@ionic/angular';
import { SQLite, SQLiteObject } from '@ionic-native/sqlite/ngx';

@Injectable({
  providedIn: 'root'
})
export class SqliteService {

  private dbInstance: SQLiteObject;
  readonly db_name: string = "gabinetedigital.db";
  readonly events: string = "Events";
  readonly expedientes: string = "Expedientes";
  readonly allprocess: string = "ALLPROCESS";
  readonly actions: string = "ACTIONS";
  readonly publications: string = "PUBLICATIONS";
  readonly chatlistroom: string = "CHATLISTROOM";
  readonly chatlistUsers: string = "CHATLISTUSERS";
  readonly chatmsg: string = "CHATMSG";
  EVENTS: Array<any>;
  EXPEDIENTES: Array<any>;
  ALLPROCESS: Array<any>;
  PROCESS: Array<any>;
  ALLACTIONS: Array<any>;
  ALLChatROOM: Array<any>;
  ALLChatUSERs: Array<any>;
  ALLCHATMSG: Array<any>;

  constructor(private platform: Platform,
    private sqlite: SQLite) {
    this.databaseConn();
  }

   databaseConn() {
    console.log('SQLDBConnect')
    if (this.platform.is('desktop') || this.platform.is('mobileweb')) {
    } else {
      console.log('SQLDBConnect22')
      this.platform.ready().then(async () => {
        console.log('SQLDBConnect33')
         this.sqlite.create({
          name: this.db_name,
          location: 'default'
        }).then(async (sqLite: SQLiteObject) => {
          this.dbInstance = sqLite;
          console.log('SQLITE INSTACE ',this.dbInstance);
          await sqLite.executeSql(`
              CREATE TABLE IF NOT EXISTS ${this.events} (
                EventId varchar(255) PRIMARY KEY, 
                Subject varchar(255),
                HasAttachments BIT,
                Location varchar(255),
                CalendarId varchar(255),
                CalendarName varchar(255),
                StartDate varchar(255),
                EndDate varchar(255),
                EventType varchar(255),
                Attendees Text,
                IsMeeting BIT,
                IsRecurring BIT,
                IsAllDayEvent BIT,
                AppointmentState INTERGER,
                TimeZone varchar(255),
                Organizer Text,
                Category varchar(255),
                EventRecurrence Text,
                Attachments Text,
                Body Text,
                Profile varchar(255),
                HumanDate varchar(255)
              )`, [])
            .then((res) => {
              console.log("Sucess Events Table created: ", res)
            })
            .catch((error) => console.log(JSON.stringify(error)));

          await sqLite.executeSql(`
              CREATE TABLE IF NOT EXISTS ${this.expedientes} (
                serialNumber varchar(255) PRIMARY KEY, 
                workflowInstanceFolio varchar(255),
                Documents Text,
                actions Text,
                activityInstanceName varchar(255),
                formURL varchar(255),
                originator Text,
                taskStartDate varchar(255),
                totalDocuments INTERGER,
                workflowDisplayName varchar(255),
                workflowID INTERGER,
                workflowInstanceDataFields Text,
                workflowInstanceID INTERGER,
                workflowName varchar(255)
              )`, [])
            .then((res) => {
              console.log("Sucess Espedientes Table created: ", res)
            })
            .catch((error) => console.log(JSON.stringify(error)));

          await sqLite.executeSql(`
          CREATE TABLE IF NOT EXISTS ${this.allprocess} (
            serialNumber varchar(255) PRIMARY KEY, 
            workflowInstanceFolio varchar(255),
            Documents Text,
            actions Text,
            activityInstanceName varchar(255),
            formURL varchar(255),
            originator Text,
            taskStartDate varchar(255),
            totalDocuments INTERGER,
            workflowDisplayName varchar(255),
            workflowID INTERGER,
            workflowInstanceDataFields Text,
            workflowInstanceID INTERGER,
            workflowName varchar(255),
            interveners Text
          )`, [])
            .then((res) => {
              console.log("Sucess AllProcess Table created: ", res)
            })
            .catch((error) => console.log(JSON.stringify(error)));

          await sqLite.executeSql(`
          CREATE TABLE IF NOT EXISTS ${this.actions} (
            ProcessId INTERGER PRIMARY KEY,
            ActionType varchar(255),
            DateBegin varchar(255),
            DateEnd varchar(255),
            Detail varchar(255),
            Description varchar(255),
            publications Text
          )`, [])
            .then((res) => {
              console.log("Sucess action Table created: ", res)
            })
            .catch((error) => console.log(JSON.stringify(error)));

            await sqLite.executeSql(`
            CREATE TABLE IF NOT EXISTS ${this.chatlistroom} (
              Id varchar(255) PRIMARY KEY,
              Uids Text,
              Usernames Text,
              LastMessage Text,
              UpdatedAt varchar(255),
              customFields Text,
              name varchar(255)
            )`, [])
              .then((res) => {
                console.log("Sucess chat list room Table created: ", res)
              })
              .catch((error) => console.log(JSON.stringify(error)));

              await sqLite.executeSql(`
              CREATE TABLE IF NOT EXISTS ${this.chatlistUsers} (
                Id varchar(255) PRIMARY KEY,
                Name varchar(255),
                Username varchar(255)
                
              )`, [])
                .then((res) => {
                  console.log("Sucess chat list users Table created: ", res)
                })
                .catch((error) => console.log(JSON.stringify(error)));

                await sqLite.executeSql(`
              CREATE TABLE IF NOT EXISTS ${this.chatmsg} (
                Id varchar(255) PRIMARY KEY,
                Attachments Text,
                Channels Text,
                File Text,
                Mentions Text,
                Msg varchar(255),
                Rid varchar(255),
                Ts varchar(255),
                U Text,
                UpdatedAt varchar(255)
              )`, [])
                .then((res) => {
                  console.log("Sucess chat msg Table created: ", res)
                })
                .catch((error) => console.log(JSON.stringify(error)));


        })
          .catch((error) => console.log(JSON.stringify(error)));

          
      }).catch((error) => {
        console.log('Platform ready error', error)
      });
    }
  }

  //addactions
  public addactions(data) {
    console.log('Action insert', data)
    this.dbInstance.executeSql(`
    INSERT OR IGNORE INTO ${this.actions} (ActionType,DateBegin,DateEnd,Description,Detail,ProcessId,publications) 
    VALUES ('${data.ActionType}','${data.DateBegin}', '${data.DateEnd}','${data.Description}','${data.Detail}','${data.ProcessId}','${data.publications}')`, [])
      .then(() => {
        console.log("action add with Success");

      }, (e) => {
        console.log(JSON.stringify(e.err));
      });
  }

  //addEvent
  public addEvent(data) {
    this.dbInstance.executeSql(`
    INSERT OR IGNORE INTO ${this.events} (EventId,Subject,HasAttachments,Location,CalendarId,CalendarName,StartDate,EndDate,EventType,Attendees,IsMeeting,IsRecurring,IsAllDayEvent,AppointmentState,TimeZone,Organizer,Category,EventRecurrence,Attachments,Body,Profile,HumanDate ) 
    VALUES ('${data.EventId}','${data.Subject}','${data.HasAttachments}','${data.Location}','${data.CalendarId}','${data.CalendarName}','${data.StartDate}','${data.EndDate}','${data.EventType}','${data.Attendees}','${data.IsMeeting}','${data.IsRecurring}',
    '${data.IsAllDayEvent}','${data.AppointmentState}','${data.TimeZone}','${data.Organizer}','${data.Category}','${data.EventRecurrence}','${data.Attachments}','${data.Body}','${data.Profile}','${data.HumanDate}')`, [])
      .then(() => {
        console.log("event add with Success");

      }, (e) => {
        console.log(JSON.stringify(e));
      });
  }

  //addExpediente
  public addExpediente(data) {
    this.dbInstance.executeSql(`
      INSERT OR REPLACE INTO ${this.expedientes} (serialNumber,workflowInstanceFolio,Documents,actions,activityInstanceName,formURL,originator,taskStartDate,totalDocuments,workflowDisplayName,workflowID,workflowInstanceDataFields,workflowInstanceID,workflowName) 
      VALUES ('${data.serialNumber}','${data.workflowInstanceFolio}', '${data.Documents}','${data.actions}','${data.activityInstanceName}','${data.formURL}','${data.originator}','${data.taskStartDate}','${data.totalDocuments}','${data.workflowDisplayName}','${data.workflowID}',
      '${data.workflowInstanceDataFields}','${data.workflowInstanceID}','${data.workflowName}')`, [])
      .then(() => {
        console.log("expediente add with Success");

      }, (e) => {
        console.log(JSON.stringify(e.err));
      });
  }

  //addprocess
  public addProcess(data) {
    this.dbInstance.executeSql(`
      INSERT OR IGNORE INTO ${this.allprocess} (serialNumber,workflowInstanceFolio,Documents,actions,activityInstanceName,formURL,originator,taskStartDate,totalDocuments,workflowDisplayName,workflowID,workflowInstanceDataFields,workflowInstanceID,workflowName) 
      VALUES ('${data.serialNumber}','${data.workflowInstanceFolio}', '${JSON.stringify(data.Documents)}','${JSON.stringify(data.actions)}','${data.activityInstanceName}','${data.formURL}','${JSON.stringify(data.originator)}','${data.taskStartDate}','${data.totalDocuments}','${data.workflowDisplayName}','${data.workflowID}',
      '${JSON.stringify(data.workflowInstanceDataFields)}','${data.workflowInstanceID}','${data.workflowName}')`, [])
      .then(() => {
        console.log("process add with Success");

      }, (e) => {
        console.log(JSON.stringify(e.err));
      });
  }

  //chatlistroom
  public addChatListRoom(data) {
    console.log('INSIDE DB CHAT LIST ROOM',data,)
    this.dbInstance.executeSql(`
      INSERT OR REPLACE INTO ${this.chatlistroom} (Id,Uids,Usernames,LastMessage,UpdatedAt,customFields,name) 
      VALUES ('${data.id}','${JSON.stringify(data.uids)}','${JSON.stringify(data.usernames)}','${JSON.stringify(data.lastMessage)}','${data.updatedat}','${JSON.stringify(data.customFields)}','${data.name}')`, [])
      .then(() => {
        console.log("chat room add with Success");

      }, (e) => {
        console.log(JSON.stringify(e.err));
      });
  }

  //chatlistusers
  public addChatListUsers(data) {
    console.log('INSIDE DB CHAT LIST ROOM',data,)
    this.dbInstance.executeSql(`
      INSERT OR REPLACE INTO ${this.chatlistUsers} (Id,Name,Username) 
      VALUES ('${data.id}','${data.name}','${data.username}')`, [])
      .then(() => {
        console.log("chat users add with Success");

      }, (e) => {
        console.log(JSON.stringify(e.err));
      });
  }

  //chatlistusers
  public addChatMSG(data) {
    console.log('INSIDE DB CHAT MSG',data,)
    this.dbInstance.executeSql(`
      INSERT OR REPLACE INTO ${this.chatmsg} (Id,Attachments,Channels,File,Mentions,Msg,Rid, Ts ,U, UpdatedAt) 
      VALUES ('${data._id}','${JSON.stringify(data.attachments)}','${JSON.stringify(data.channels)}','${JSON.stringify(data.file)}','${JSON.stringify(data.mentions)}','${data.msg}','${data.rid}','${data.ts}','${JSON.stringify(data.u)}','${data._updatedAt}')`, [])
      .then(() => {
        console.log("chat msg add with Success");

      }, (e) => {
        console.log(JSON.stringify(e.err));
      });
  }

  //updateevent
  public updateEvent(data) {
    this.dbInstance.executeSql(`
    INSERT OR REPLACE INTO ${this.events} (EventId,Subject,HasAttachments,Location,CalendarId,CalendarName,StartDate,EndDate,EventType,Attendees,IsMeeting,IsRecurring,IsAllDayEvent,AppointmentState,TimeZone,Organizer,Category,EventRecurrence,Attachments,Body,Profile,HumanDate ) 
    VALUES ('${data.EventId}','${data.Subject}','${data.HasAttachments}','${data.Location}','${data.CalendarId}','${data.CalendarName}','${data.StartDate}','${data.EndDate}','${data.EventType}','${data.Attendees}','${data.IsMeeting}','${data.IsRecurring}',
    '${data.IsAllDayEvent}','${data.AppointmentState}','${data.TimeZone}','${data.Organizer}','${data.Category}','${data.EventRecurrence}','${data.Attachments}','${data.Body}','${data.Profile}','${data.HumanDate}')`, [])
      .then(() => {
        console.log("event update with Success");

      }, (e) => {
        console.log(JSON.stringify(e));
      });
  }

  //updateActions
  public updateactions(id, data) {
    try {
      console.log("update action data", data)
      this.dbInstance.executeSql(`
      UPDATE ${this.actions} SET publications = ? WHERE ProcessId = ${id}`, [data])
        .then(() => {
          console.log("action update with Success");

        }, (e) => {
          console.log(JSON.stringify(e.err));
        });
    } catch(error) {}

  }


  //updateprocess
  public updateProcess(data) {
    this.dbInstance.executeSql(`
        INSERT OR REPLACE INTO ${this.allprocess} (serialNumber,workflowInstanceFolio,Documents,actions,activityInstanceName,formURL,originator,taskStartDate,totalDocuments,workflowDisplayName,workflowID,workflowInstanceDataFields,workflowInstanceID,workflowName) 
        VALUES ('${data.serialNumber}','${data.workflowInstanceFolio}', '${JSON.stringify(data.Documents)}','${JSON.stringify(data.actions)}','${data.activityInstanceName}','${data.formURL}','${JSON.stringify(data.originator)}','${data.taskStartDate}','${data.totalDocuments}','${data.workflowDisplayName}','${data.workflowID}',
        '${JSON.stringify(data.workflowInstanceDataFields)}','${data.workflowInstanceID}','${data.workflowName}')`, [])
      .then(() => {
        console.log("process add with Success");

      }, (e) => {
        console.log(JSON.stringify(e.err));
      });
  }

  //updateAttachment
  updateUser(id, document,) {
    let data = [document];
    return this.dbInstance.executeSql(`UPDATE ${this.allprocess} SET Documents = ? WHERE serialNumber = ${id}`, [document]).then(() => {
      console.log("process attachment updated")
    })
  }
  //updateAttachment
  updateProcessInterveners(id, interveners,) {
    let data = [document];
    return this.dbInstance.executeSql(`UPDATE ${this.allprocess} SET interveners = ? WHERE serialNumber = ${id}`, [interveners]).then(() => {
      console.log("process interveners updated")
    })
  }
  //getAllEvents
  getAllEvents() {
    var hashattachment = false;
    var ismeeting = false;
    var isrecurring = false;
    var isallday = false;
    return this.dbInstance.executeSql(`SELECT * FROM ${this.events}`, []).then((res) => {
      this.EVENTS = [];
      if (res.rows.length > 0) {
        for (var i = 0; i < res.rows.length; i++) {
          if (res.rows.item(i).HasAttachments === "true") {
            hashattachment = true
          }
          if (res.rows.item(i).IsMeeting === "true") {
            ismeeting = true
          }
          if (res.rows.item(i).IsRecurring === "true") {
            isrecurring = true
          }
          if (res.rows.item(i).IsAllDayEvent === "true") {
            isallday = true
          }
          let event = {
            EventId: res.rows.item(i).EventId,
            HasAttachments: hashattachment,
            Subject: res.rows.item(i).Subject,
            Location: res.rows.item(i).Location,
            CalendarId: res.rows.item(i).CalendarId,
            CalendarName: res.rows.item(i).CalendarName,
            StartDate: res.rows.item(i).StartDate,
            EndDate: res.rows.item(i).EndDate,
            EventType: res.rows.item(i).EventType,
            Attendees: res.rows.item(i).Attendees,
            IsMeeting: ismeeting,
            IsRecurring: isrecurring,
            IsAllDayEvent: isallday,
            AppointmentState: res.rows.item(i).AppointmentState,
            TimeZone: res.rows.item(i).TimeZone,
            Organizer: res.rows.item(i).Organizer,
            Category: res.rows.item(i).Category,
            EventRecurrence: res.rows.item(i).EventRecurrence,
            Attachments: res.rows.item(i).Attachments,
            Profile: res.rows.item(i).Profile,
            HumanDate: res.rows.item(i).HumanDate

          }
          this.EVENTS.push(event);
        }

        return this.EVENTS;
      }
    }, (e) => {
      console.log(" Get all events error", JSON.stringify(e));
    });
  }

  getAllExpedientes() {
    return this.dbInstance.executeSql(`SELECT * FROM ${this.expedientes}`, []).then((res) => {
      this.EXPEDIENTES = [];
      if (res.rows.length > 0) {
        for (var i = 0; i < res.rows.length; i++) {
          this.EXPEDIENTES.push(res.rows.item(i));
        }
        return this.EXPEDIENTES;
      }
    }, (e) => {
      console.log(" Get all expedientes error", JSON.stringify(e));
    });
  }

  getAllProcess() {
    return this.dbInstance.executeSql(`SELECT * FROM ${this.allprocess}`, []).then((res) => {
      this.ALLPROCESS = [];
      if (res.rows.length > 0) {
        for (var i = 0; i < res.rows.length; i++) {
          this.ALLPROCESS.push(res.rows.item(i));
        }
        return this.ALLPROCESS;
      }
    }, (e) => {
      console.log(" Get all process error", JSON.stringify(e));
    });
  }

  //getAllAtions
  getAllActions() {
    return this.dbInstance.executeSql(`SELECT * FROM ${this.actions}`, []).then((res) => {
      this.ALLACTIONS = [];
      if (res.rows.length > 0) {
        for (var i = 0; i < res.rows.length; i++) {
          this.ALLACTIONS.push(res.rows.item(i));
        }
        return this.ALLACTIONS;
      }
    }, (e) => {
      console.log(" Get all actions error", JSON.stringify(e));
    });
  }

  //getAllChatRoom
  getAllChatRoom() {
    return this.dbInstance.executeSql(`SELECT * FROM ${this.chatlistroom}`, []).then((res) => {
      this.ALLChatROOM = [];
      if (res.rows.length > 0) {
        for (var i = 0; i < res.rows.length; i++) {
          this.ALLChatROOM.push(res.rows.item(i));
        }
        return this.ALLChatROOM;
      }
    }, (e) => {
      console.log(" Get all chat room error", JSON.stringify(e));
    });
  }

  //getAllChatUsers
  getAllChatUsers() {
    return this.dbInstance.executeSql(`SELECT * FROM ${this.chatlistUsers}`, []).then((res) => {
      this.ALLChatUSERs = [];
      if (res.rows.length > 0) {
        for (var i = 0; i < res.rows.length; i++) {
          this.ALLChatUSERs.push(res.rows.item(i));
        }
        return this.ALLChatUSERs;
      }
    }, (e) => {
      console.log(" Get all chat users error", JSON.stringify(e));
    });
  }

  //getAllChatMSG
  getAllChatMSG(roomId) {
    return this.dbInstance.executeSql(`SELECT * FROM ${this.chatmsg} WHERE Rid = ?`, [roomId]).then((res) => {
      this.ALLCHATMSG = [];
      if (res.rows.length > 0) {
        for (var i = 0; i < res.rows.length; i++) {
          this.ALLCHATMSG.push(res.rows.item(i));
        }
        return this.ALLCHATMSG;
      }
    }, (e) => {
      console.log(" Get all chat users error", JSON.stringify(e));
    });
  }
  //getlistOfEventAprove
  getListOfEventAprove(process, type) {
    return this.dbInstance.executeSql(`SELECT * FROM ${this.allprocess} WHERE workflowDisplayName = ? OR workflowDisplayName = ? `, [process, type]).then((res) => {
      this.ALLPROCESS = [];
      if (res.rows.length > 0) {
        for (var i = 0; i < res.rows.length; i++) {
          this.ALLPROCESS.push(res.rows.item(i));
        }
        return this.ALLPROCESS;
      }
    }, (e) => {
      console.log(" Get all process error", JSON.stringify(e));
    });
  }

  //getDespachosProcess
  getDespachosProcess(process) {
    return this.dbInstance.executeSql(`SELECT * FROM ${this.allprocess} WHERE activityInstanceName = ?`, [process]).then((res) => {
      this.ALLPROCESS = [];
      if (res.rows.length > 0) {
        for (var i = 0; i < res.rows.length; i++) {
          this.ALLPROCESS.push(res.rows.item(i));
        }
        return this.ALLPROCESS;
      }
    }, (e) => {
      console.log(" Get all process error", JSON.stringify(e));
    });
  }

  //getprocessByworkflow
  getprocessByworkflow(process) {
    return this.dbInstance.executeSql(`SELECT * FROM ${this.allprocess} WHERE workflowDisplayName = ? `, [process]).then((res) => {
      this.ALLPROCESS = [];
      if (res.rows.length > 0) {
        for (var i = 0; i < res.rows.length; i++) {
          this.ALLPROCESS.push(res.rows.item(i));
          console.log('getEXPEDIENTE DB LOOP')
        }
        return this.ALLPROCESS;
      }
    }, (e) => {
      console.log(" Get all process error", JSON.stringify(e));
    });
  }

  //getprocessByworkflowpedido
  getprocessByworkflowpedido(process, process2) {
    return this.dbInstance.executeSql(`SELECT * FROM ${this.allprocess} WHERE workflowDisplayName = ? OR workflowDisplayName = ? `, [process, process2]).then((res) => {
      this.ALLPROCESS = [];
      if (res.rows.length > 0) {
        for (var i = 0; i < res.rows.length; i++) {
          this.ALLPROCESS.push(res.rows.item(i));
        }
        return this.ALLPROCESS;
      }
    }, (e) => {
      console.log(" Get all process error", JSON.stringify(e));
    });
  }

  getProcessById(serial) {
    return this.dbInstance.executeSql(`SELECT * FROM ${this.allprocess} WHERE serialNumber = ? `, [serial]).then((res) => {
      this.PROCESS = [];
      if (res.rows.length > 0) {
        for (var i = 0; i < res.rows.length; i++) {
          this.PROCESS.push(res.rows.item(i))
        }
        return this.PROCESS;
      }
    }, (e) => {
      console.log(" Get process by serial error", JSON.stringify(e));
    });
  }

  //getActionById
  getActionById(id) {
    return this.dbInstance.executeSql(`SELECT * FROM ${this.actions} WHERE ProcessId = ? `, [id]).then((res) => {
      this.ALLACTIONS = [];
      if (res.rows.length > 0) {
        for (var i = 0; i < res.rows.length; i++) {
          this.ALLACTIONS.push(res.rows.item(i))
        }
        return this.ALLACTIONS;
      }
    }, (e) => {
      console.log(" Get actions by processId error", JSON.stringify(e));
    });
  }

  //getEventBy id
  getEventById(id) {

    var hashattachment = false;
    var ismeeting = false;
    var isrecurring = false;
    var isallday = false;
    var body;
    var attendes;
    var organizer;
    var eventrecurrence;
    var attachment;

    return this.dbInstance.executeSql(`SELECT * FROM ${this.events} WHERE EventId = ? `, [id]).then((res) => {
      this.EVENTS = [];
      if (res.rows.length > 0) {
        for (var i = 0; i < res.rows.length; i++) {
          if (res.rows.item(i).HasAttachments === "true") {
            hashattachment = true
          }
          if (res.rows.item(i).IsMeeting === "true") {
            ismeeting = true
          }
          if (res.rows.item(i).IsRecurring === "true") {
            isrecurring = true
          }
          if (res.rows.item(i).IsAllDayEvent === "true") {
            isallday = true
          }
          /* if (res.rows.item(i).Body != "") {
            body = JSON.parse(res.rows.item(i).Body);
          }
          if (res.rows.item(i).Attendees !="") {
            attendes = JSON.parse(res.rows.item(i).Attendees);
          }
          if(res.rows.item(i).Organizer !=""){
            organizer = JSON.parse(res.rows.item(i).Organizer);
          }
          if(res.row.item(i).EventRecurrence != ""){
            eventrecurrence = JSON.parse(res.row.item(i).EventRecurrence);
          }
          if(res.row.item(i).Attachments != ""){
            attachment = JSON.parse(res.row.item(i).Attachments);
          }
 */

          let event = {
            EventId: res.rows.item(i).EventId,
            HasAttachments: hashattachment,
            Subject: res.rows.item(i).Subject,
            Location: res.rows.item(i).Location,
            CalendarId: res.rows.item(i).CalendarId,
            CalendarName: res.rows.item(i).CalendarName,
            StartDate: res.rows.item(i).StartDate,
            EndDate: res.rows.item(i).EndDate,
            EventType: res.rows.item(i).EventType,
            Attendees: res.rows.item(i).Attendees,
            IsMeeting: ismeeting,
            IsRecurring: isrecurring,
            IsAllDayEvent: isallday,
            Body: res.rows.item(i).Body,
            AppointmentState: res.rows.item(i).AppointmentState,
            TimeZone: res.rows.item(i).TimeZone,
            Organizer: res.rows.item(i).Organizer,
            Category: res.rows.item(i).Category,
            EventRecurrence: res.rows.item(i).EventRecurrence,
            Attachments: res.rows.item(i).Attachments
          }
          this.EVENTS.push(event);
        }

        return this.EVENTS;
      }
    }, (e) => {
      console.log(" Get events by id error", JSON.stringify(e));
    });
  }

  deleteAllTables() {
    this.deleteeventsTable();
    this.deleteallprocessTable();
    this.deleteactionsTable();
    this.deletepublicationsTable();

    console.log('All tables deleted')
  }

  deleteeventsTable() {
    return this.dbInstance.executeSql("DELETE from "+ this.events).then((res) => {
      console.log('DELETE EVENT TABLE RESULT ', res)
    });
  }

  deleteallprocessTable() {
    return this.dbInstance.executeSql("DELETE from "+ this.allprocess).then((res) => {
      console.log('DELETE ALLPROCESS TABLE RESULT ', res)
    });
  }

  deleteactionsTable() {
    return this.dbInstance.executeSql("DELETE from "+ this.actions).then((res) => {
      console.log('DELETE actions TABLE RESULT ', res)
    });
  }

  deletepublicationsTable() {
    return this.dbInstance.executeSql("DELETE from "+ this.publications).then((res) => {
      console.log('DELETE publications TABLE RESULT ', res)
    });
  }
}
