import React from 'react';
import { fixedurl, baseurl, version, db, OQAD_TimeConst, OQAD_TimeConstimeConst } from '../constants/constants';
import Marker, { ImageFormat, Position } from 'react-native-image-marker';
import moment from 'moment';
import { notify } from '../components/notify';
import { AppTables, Table_Structure } from '../constants/tableConstants';
import { Dimensions, Platform } from 'react-native';
import ImageResizer from 'react-native-image-resizer';
import { get_item } from '../components/localStorage';
import ImageMarkText from '../components/ImageMarkText';
import * as RNFS from 'react-native-fs';

export async function getProjectData(pid) {
  let post_data = { "ProjectCode": pid, "AppName": "Manager" }
  return await fetch(fixedurl, {
    method: 'post',
    headers: {
      Accept: 'application/json',
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(post_data),
  })
    .then(response => {
      return response.json();
    })
    .then(res => {
      // console.log("project datares",res);
      let appdata = res.GetAppSetting || [];
      let appdata1 = appdata.length > 0 ? appdata[0] : {};
      appdata1.success = true;
      return appdata1;
    })
    .catch(err => {
      console.log('getProjectData error', err);
      return { success: false };
    });
}

export async function login(url, indata) {
  const pdata = JSON.stringify({
    UserName: indata.un,
    Password: indata.pass,
    Intime: indata.Intime,
    Latitude: indata.lat,
    Longitude: indata.lng,
    Appversion: version,
    Attmode: '0',
    Networkstatus: '0',
    Manufacturer: indata.manufacturer,
    ModelNumber: indata.model,
    OSVersion: indata.os,
    IMEINumber1: indata.imeiNo1,
    IMEINumber2: indata.imeiNo2,
  });

  console.log(pdata);


  return await fetch(url, {
    method: 'post',
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json',
    },
    body: pdata,
  })
    .then(response => {
      return response.json();
    })
    .then(res => {
      let resdata = JSON.parse(res);

      if (resdata.DeviceLoginSup != null) {
        resdata = resdata.DeviceLoginSup.length > 0 ? resdata.DeviceLoginSup[0] : {};
        resdata.success = true;
      } else {
        resdata = { success: false, error: 'Invalid username or password' };
      }
      return resdata;
    })
    .catch(err => {
      console.log('login error', err);
      let networkErr = true;
      return { success: false, error: err, networkErr: networkErr };
    });
}

export async function getDownloadJson(url, indata) {
  let postdata = {
    Downloadtype: indata.Downloadtype,
    Username: indata.username,
    Param1: indata.empid,
    Param2: indata?.storeWisePjp ? 1 : 0,
  };
  console.log('postdata==>', url, postdata);
  return await fetch(url, {
    method: 'post',
    headers: {
      Accept: 'application/json',
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(postdata),
  })
    .then(response => {
      // console.log('response',response)
      return response.json();
    })
    .then((res) => {
      console.log('res', res);
      let resd = JSON.parse(res);
      return resd;
    })
    .catch(err => {
      console.log('getdashboard error', err);
      return { success: false };
    });
}

export async function getDownloadJson12(url, postdata) {
  return await fetch(url, {
    method: 'post',
    headers: {
      Accept: 'application/json',
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(postdata),
  })
    .then(response => {
      return response.json();
    })
    .then((res) => {
      // console.log('res',res);
      if (url.includes('api1.parinaam.in')) {
        var resd = res;
      }
      else {
        let colname = res.replace(/[$$]/g, ' ').replace(/Percent/g, '%');
        var resd = JSON.parse(colname);
      }

      return resd;
    })
    .catch(err => {
      console.log('getdashboard error', err);
      return err;
    });
}

export async function getDownloadJson1(url, postdata) {
  return await fetch(url, {
    method: 'post',
    headers: {
      Accept: 'application/json',
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(postdata),
  })
    .then(response => {
      return response.json();
    })
    .then((res) => {
      // console.log('res',res);
      if (url.includes('api1.parinaam.in')) {
        var resd = res;
      }
      else {
        var resd = JSON.parse(res);
      }

      return resd;
    })
    .catch(err => {
      console.log('getdashboard error', err);
      return err;
    });
}

export async function UploadData(url, indata) {
  return await fetch(url, {
    method: 'post',
    headers: {
      Accept: 'application/json',
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(indata),
  })
    .then(response => {

      return response.json();
    })
    .then((res) => {
      console.log('resjson:', typeof res);

      if (typeof res === 'object' && res !== null) {
        return res;

      } else {

        let resd = JSON.parse(res);

        console.log('resjson:1', res);
        return resd;
      }

    })
    .catch(err => {
      console.log('UploadData error', err);
      return { success: false, error: err };
    });
}

export async function UploadData2(url, indata) {
  return await fetch(url, {
    method: 'post',
    headers: {
      Accept: 'application/json',
      'Content-Type': 'application/json; charset=utf-8',
    },

    body: JSON.stringify(indata),
  })
    .then(response => {
      // console.log('myresp:',response)
      return response.json();
    })
    .then((res) => {
      return res;
    })
    .catch(err => {
      console.log('UploadData error', err);
      return { success: false, error: true };
    });
}

export async function UploadFormData(url, formData) {
  console.log('UploadFormData', url + JSON.stringify(formData))
  return await fetch(url, {
    method: 'post',
    headers: new Headers({ 'Content-Type': 'multipart/form-data', }),
    body: formData,
  })
    .then(response => {
      // console.log('response',response);
      return response.text();
    })
    .then((res) => {
      console.log('res', res);
      return res;
    })
    .catch(err => {
      console.log('UploadData error', err);
      return { success: false, error: err };
    });
}

export async function DownloadData(props, { isDataDownloaded = false }) {
  if (isDataDownloaded) {
    return;
  }
  let d1 = new Date();
  let today = moment(d1).format('MM/DD/YYYY');

  return new Promise((resolve, reject) => {
    db.transaction(async function (txn) {

      function deletePrevData() {
        console.log('deletePrevData');
        // delete all previous data
        let tables_keys = Object.keys(AppTables);
        let app_index = 0;
        for (const key in AppTables) {
          txn.executeSql(`Delete from ${AppTables[key]} where ADDED_DATE!='${today}'`, [], function (txnd, txnresd) {
            if (app_index == tables_keys.length - 1) {
              resolve(true);
            }
            app_index++;
          },
            function (txn1, txnerr) {
              console.log(txnerr);
              if (app_index == tables_keys.length - 1) {
                resolve(true);
              }
              app_index++;
            });
        }
      }

      for (const i in Table_Structure) {
        const table = Table_Structure[i];
        await txn.executeSql(table.SqlText, [],
          function (txn2, txnres2) {
            if (i == Table_Structure.length - 1) {
              deletePrevData();
            }
          },
          function (txn2, txnerr) {
            console.log(txnerr);
            if (i == Table_Structure.length - 1) {
              deletePrevData();
            }
          }
        );
      }

    });
  }).catch((err) => {

  })
}

export async function UpdateStoreStatus(props, data, callback = () => { }) {
  let d1 = new Date();
  let today = moment(d1).format('MM/DD/YYYY');

  return new Promise((resolve, reject) => {

    if (data != null && data.UploadStatus != null && data.UploadStatus != '') {
      db.transaction(async function (txn) {

        let { StoreId, UploadStatus, tbname, EmpId, STORE_ID } = data;

        let q = `UPDATE ${tbname} SET UploadStatus='${UploadStatus}' WHERE StoreId='${StoreId || STORE_ID}' and MerchandiserId='${EmpId}' and VisitDate='${today}' `;
        let q2 = `UPDATE ${AppTables.COVERAGE_DATA} SET STATUS='${UploadStatus}' WHERE STORE_ID='${StoreId || STORE_ID}' and EMP_ID='${EmpId}' and VISIT_DATE='${today}' `;

        console.log("update store status q:", q);
        await txn.executeSql(q2, [], async function (txn2, txnres2) {
          console.log('store status updated', UploadStatus,);
        }, function (txn2, txnerr) { console.log(txnerr); resolve(false); });

        console.log("update store status q:", q);
        await txn.executeSql(q, [], async function (txn2, txnres2) {
          console.log('store status updated', UploadStatus,);
          callback(txnres2);
          resolve(true);
        }, function (txn2, txnerr) { console.log(txnerr); resolve(false); });

      });
    }
    else {
      resolve(false);
    }
  }).then((val) => {
    return val;
  }).catch((err) => {
    console.log(err);
    return false;
  });


}

export async function getKPIS(MenuList) {
  let allKpis = [];

  return Promise.all(
    MenuList.map((item) => {
      let ScreenName = item.ScreenName || "";
      let MenuId = item.MenuId || 0;

      switch (ScreenName) {
        case "STOREAUDIT":
          allKpis.push({ MenuId, KPI: "STOREAUDIT" });
          return { MenuId, KPI: "STOREAUDIT" };

        case "STOREPHOTO":
          allKpis.push({ MenuId, KPI: "StorePhoto" });
          return { MenuId, KPI: "StorePhoto" };

        case "COMPVISI":
          allKpis.push({ MenuId, KPI: "CompVis" });
          return { MenuId, KPI: "CompVis" };

        case "COMPPROMO":
          allKpis.push({ MenuId, KPI: "CompPromo" });
          return { MenuId, KPI: "CompPromo" };

        case "VISIBILITYAUDIT":
          allKpis.push({ MenuId, KPI: "VISIBILITYAUDIT" });
          return { MenuId, KPI: "VISIBILITYAUDIT" };

        case "POSSALE":
          allKpis.push({ MenuId, KPI: "POSSALE" });
          return { MenuId, KPI: "POSSALE" };

        default:
          return null;
      }
    })
  ).then(() => {
    return allKpis;
  });
}


export async function getIf_UserIsManager(props) {
  let loginInfo = await get_item('loginInfo');
  let loginDetails = JSON.parse(loginInfo);
  let designation = loginDetails.Designation != null ? loginDetails.Designation : '';

  let ManagersList = props.SUP_ManagerDesigList != null && props.SUP_ManagerDesigList != "" && typeof props.SUP_ManagerDesigList == "string" ? props.SUP_ManagerDesigList.split(",") : [];
  console.log("user designatio in DT:", designation, ManagersList, props.SUP_ManagerDesigList);
  let userIsManager = designation != "" && designation != null && Array.isArray(ManagersList) && ManagersList.indexOf(designation) >= 0;
  console.log("userIsManager:", userIsManager);
  return userIsManager;
}

export async function getAttendNonWorkingRsns() {
  let d1 = new Date();
  let d2 = moment(d1).format('MM/DD/YYYY');
  let token = await get_item('loginToken');
  let loginInfo = await get_item('loginInfo');
  const loginDetails = JSON.parse(loginInfo);

  let nonWrkRsns = [];

  return new Promise((resolve, reject) => {
    db.transaction(async function (txn) {
      let q = `SELECT * FROM Sup_NonWorkingReason where ShowAttendance='1'`;

      await txn.executeSql(q, [], async function (txn2, txnres2) {
        console.log('data len:', txnres2.rows.length);
        if (txnres2.rows.length > 0) {
          // show from local

          for (var i = 0; i < txnres2.rows.length; i++) {
            let sdata = txnres2.rows.item(i);
            nonWrkRsns.push(sdata);
            if (i == (txnres2.rows.length - 1)) {
              resolve(nonWrkRsns);
            }
          }
        }
        else {
          resolve(nonWrkRsns);
        }
      }, function (txn2, txnerr) { console.log(txnerr); resolve(nonWrkRsns); });
    });
  }).catch((err) => {
    console.log(err);
    return nonWrkRsns;
  })

}

export function get_rowColSettings(colVal, colName, row) {

  let res = { "color": '', "fontsize": "", "bold": 0 };
  let gset_obj = row["Color"] != null && row["Color"] != null != '' ? (row["Color"]) : {};
  if (Object.keys(gset_obj).length > 0 && colVal != null && colVal != '') {
    let settings_Obj = gset_obj;

    let color_obj = settings_Obj["colors"] != null && typeof settings_Obj["colors"] == 'object' ? settings_Obj["colors"] : {};
    let column_settings = color_obj[colName] != null && color_obj[colName] != '' ? color_obj[colName] : [];

    if (column_settings.length > 0) {
      for (let i = 0; i < column_settings.length; i++) {
        let colset_obj = column_settings[i];

        // if min and max both is present
        if (colset_obj["min"] != null && Math.round(colVal) >= colset_obj["min"] && colset_obj["max"] != null && Math.round(colVal) <= colset_obj["max"]) {

          res = { "color": colset_obj.color, "fontsize": colset_obj.fontsize, "bold": colset_obj.bold };
          return res;
        }
        // if only min is present
        else if (colset_obj["min"] != null && Math.round(colVal) >= colset_obj["min"] && (colset_obj["max"] == null || colset_obj["max"] == '')) {

          res = { "color": colset_obj.color, "fontsize": colset_obj.fontsize, "bold": colset_obj.bold };
          return res;
        }
        // if only max is present
        else if (colset_obj["max"] != null && Math.round(colVal) <= colset_obj["max"] && (colset_obj["min"] == null || colset_obj["min"] == '')) {

          res = { "color": colset_obj.color, "fontsize": colset_obj.fontsize, "bold": colset_obj.bold };
          return res;
        }

        if (i == column_settings.length - 1) {
          console.log("end")
          return res;
        }
      }
    }
    else {
      return res;
    }
  }
  else {
    return res
  }
}

const formatImagePath = (path) => {
  if (Platform.OS === 'ios') {
    return path.replace('file://', '');
  }
  return path;
};


export const marktext1 = async (text = '', imgurl = '', x = 50, y = 50) => {
  if (imgurl != '' && text != '') {
    const formattedImg = imgurl//"file:///private/var/mobile/Containers/Data/Application/16B5B2ED-8E45-44C0-A38B-CFC623F639A9/tmp/621C929F-CF0D-466C-B7FC-82373E05D013.jpg";

    console.log("formattedImg--mt1", formattedImg, text);

    return Marker.markText({
      backgroundImage: {
        src: formattedImg
      },
      watermarkTexts: [
        {
          text: text,
          position: {
            X: x,
            Y: y
          },
          style: {
            color: '#ff0000',
            fontSize: 40,
            textBackgroundStyle: {
              type: 'stretchX',
              paddingX: 30,
              paddingY: 10,
              color: 'transparent'
            }
          }
        }
      ],
      scale: 1,
      quality: 100,
      maxSize: 2048,
      saveFormat: 'jpg',
    })
      .then((res) => {
        console.log("uri--mt1", res);
        return { success: true, uri: res };
      })
      .catch((err) => {
        console.log("err--wr", err);
        return { success: false, error: err };
      });
  }
  else {
    return { success: false, imagenotfound: true };
  }
}

// old code

export const marktext2 = async (text = '', imgurl = '', imgWidth, imgHeight) => {
  if (imgurl && text) {
    try {
      console.log("Original image URL:", imgurl);

      // Normalize the URI for Android
      let normalizedUri = imgurl;
      if (Platform.OS === 'android') {
        if (!imgurl.startsWith('file://') && !imgurl.startsWith('content://')) {
          normalizedUri = 'file://' + imgurl;
        }
      }

      console.log("Normalized URI:", normalizedUri);

      // Check if file exists
      const fileExists = await RNFS.exists(
        Platform.OS === 'android' ? normalizedUri.replace('file://', '') : normalizedUri
      );

      if (!fileExists) {
        console.log("File does not exist at path:", normalizedUri);
        return { success: false, error: 'Image file not found' };
      }

      // Get file info to verify it's a valid image
      const fileInfo = await RNFS.stat(
        Platform.OS === 'android' ? normalizedUri.replace('file://', '') : normalizedUri
      );
      console.log("File info:", fileInfo);

      const markerResult = await Marker.markText({
        backgroundImage: {
          uri: normalizedUri,
          src: normalizedUri
        },
        watermarkTexts: [
          {
            text: text,
            position: {
              position: 'bottomLeft'
            },
            style: {
              color: '#ff0000',
              fontName: 'Arial-BoldItalicMT',
              fontSize: 20,
              textBackgroundStyle: {
                type: 'stretchX',
                paddingX: 30,
                paddingY: 10,
                color: '#fff'
              }
            }
          }
        ],
        scale: 1,
        quality: 100,
        maxSize: 2048,
        saveFormat: 'jpg',
      });

      console.log("Marker result:", markerResult);

      // Continue with resizing...

      let uri = Platform.OS == 'android' ? 'file://' + markerResult : markerResult;
      // return {success:true,uri:uri};
      return await ImageResizer.createResizedImage(uri, imgWidth, imgHeight, 'JPEG', 35, 0, null, false, { onlyScaleDown: true })
        .then(response => {
          let size = bytesToSize(response.size);
          console.log('reduced filesize:', size);
          // let fileparts= response.uri.split("/");
          // let filename=fileparts[fileparts.length-1];
          // let destPath1=RNFS.DownloadDirectoryPath+"/"+filename;
          // RNFS.copyFile(response.uri,destPath1);
          return { success: true, uri: response.uri };
        })

    } catch (err) {
      console.log("Error in marktext2:", err);
      return { success: false, error: err.message || err };
    }
  } else {
    return {
      success: false,
      imagenotfound: !imgurl,
      textnotfound: !text
    };
  }
};




export async function RestoreProjectInProps(props) {
  // clear_item('firsttime');clear_item('islogin');clear_item('mpin');clear_item('loginToken');
  if (props.baseurl == '' || props.baseurl == null || props.baseurl == undefined) {
    let projectInfo = await get_item('projectInfo');
    let projectCode = await get_item('projectCode');
    let projectDetails = projectInfo != null ? JSON.parse(projectInfo) : {};

    let pdata = getProjectInfo(projectDetails)
    //set project info in global redux state
    props.set_project(pdata);
  }
}

export function getProjectInfo(projectDetails, projectCode, AppClearData) {
  let imgurl = projectDetails.imageUploadURL != null ? projectDetails.imageUploadURL + '/' : '';
  const pdata = {
    pid: (projectCode || ''),
    pname: (projectDetails.projectName || ''),
    pcode: (projectDetails.ProjectCode || ''),
    alldata: projectDetails,
    baseurl: (projectDetails.baseURL || baseurl),
    companylogo: (projectDetails.login_logo_Url || ''),
    splashlogo: (projectDetails.splash_logo_Url || ''),
    drawerlogo: (projectDetails.menu_top_logo || ''),
    imageUploadUrl: imgurl,
    GeoFenceEnable: (projectDetails.GeoFenceEnable_checkin != null && projectDetails.GeoFenceEnable_checkin == 1),
    GeoFenceRadius: (projectDetails.GeoFenceRadius_checkin || 0),
    GFEnable_checkout: (projectDetails.GeoFenceEnable_checkout != null && projectDetails.GeoFenceEnable_checkout == 1),
    SUP_StorewisePJP: (projectDetails.SUP_StorewisePJP != null && projectDetails.SUP_StorewisePJP == 1),
    GFRadius_checkout: (projectDetails.GeoFenceRadius_checkout || 0),
    CheckOut_PhotoReq: projectDetails.PhotoRequired_Checkout,
    OQAD_TimeOut: projectDetails.OQAD_TimeOut != null ? projectDetails.OQAD_TimeOut : OQAD_TimeConstimeConst,
    SUP_ManagerDesigList: (projectDetails.SUP_ManagerDesigList || ""),
    Clear_storage: AppClearData != null ? AppClearData : false,
    DownloadKey: projectDetails.DownloadKey != null ? projectDetails.DownloadKey : '',
    // DownloadKey: '',
    
    ShowDBPOSM: projectDetails.ShowDBPOSM != null ? projectDetails.ShowDBPOSM : false,
    ShowNPND: projectDetails.ShowNPND != null ? projectDetails.ShowNPND : false,
    ShowNPNDLabel: projectDetails.ShowNPNDLabel != null ? projectDetails.ShowNPNDLabel : false,
    ShowImageAudit: projectDetails.ShowImageAudit != null ? projectDetails.ShowImageAudit : false,
    Show_OldMTDReports: projectDetails.Show_OldMTDReports == 1 || projectDetails.Show_OldMTDReports == "true" ? true : false,
    ShowDashboard: projectDetails.ShowDashboard == 1 || projectDetails.ShowDashboard == "true" ? true : false,
    ManagerAppConfig: projectDetails.ManagerAppConfig != null && projectDetails.ManagerAppConfig,

    // store search

    ShowStoreSearch: projectDetails.ShowStoreSearch == 1 || projectDetails.ShowStoreSearch == "true" ? true : false,
    ShowStoreSearchLabel: projectDetails.ShowStoreSearchLabel != null ? projectDetails.ShowStoreSearchLabel : '',


  };
  return pdata;
}

export function checkRange(lat1, lon1, lat2, lon2) {
  var R = 6371; // km (change this constant to get miles)
  var dLat = (lat2 - lat1) * Math.PI / 180;
  var dLon = (lon2 - lon1) * Math.PI / 180;
  var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
    Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) *
    Math.sin(dLon / 2) * Math.sin(dLon / 2);
  var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
  var d = R * c;
  return Math.round(d * 1000);
}


export function cal_distance(lat1, lon1, lat2, lon2) {
  var p = 0.017453292519943295;    // Math.PI / 180
  var c = Math.cos;
  var a = 0.5 - c((lat2 - lat1) * p) / 2 +
    c(lat1 * p) * c(lat2 * p) *
    (1 - c((lon2 - lon1) * p)) / 2;
  R = 6371;// km
  return Math.asin(Math.sqrt(a)) * 2 * R; //12742 miles
}

export function bytesToSize(bytes) {
  var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
  if (bytes == 0) return '0 Byte';
  var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
  return Math.round(bytes / Math.pow(1024, i), 2) + ' ' + sizes[i];
}

export async function getKPIFields(menu1) {
  return new Promise((resolve, reject) => {
    db.transaction(async function (txn) {
      let q = `select * from Mapping_MenuConfiguration_Sup where ScreenName='${menu1.ScreenName}'`;
      await txn.executeSql(q, [], async function (txn2, txnres) {
        if (txnres.rows.length > 0) {
          let arr = [];
          for (var i = 0; i < txnres.rows.length; i++) {
            let data = txnres.rows.item(i);
            let isenable = data.KPIFieldEnable == 'true' || data.KPIFieldEnable == 1 ? true : false;
            data['KPIFieldEnable'] = isenable;
            arr.push(data);
            if (i == txnres.rows.length - 1) {
              resolve(arr)
            }
          }
        }
        else {
          resolve([])
        }
      }, function (txn2, txnerr) { console.log(txnerr); resolve([]) },);
    });
  }).then((val) => {
    return val;
  }).catch((err) => {
    console.log(err);
    return [];
  });
}

export function validateNumber(val, type = '', showMsg = true) {
  let isValid = true;
  if (type == 'numeric' && val != '') {
    let regex = new RegExp(/^\d+$/);
    let isNUmeric = regex.test(val);
    if (!isNUmeric) {
      isValid = false;
      if (showMsg) notify('Please enter whole numbers only', 'SHORT');
    }
  }
  else if (type == 'decimal' && val != '') {
    let regex = new RegExp(/^\d*\.?\d*$/);
    let isNUmeric = regex.test(val);
    if (!isNUmeric) {
      isValid = false;
      if (showMsg) notify('Please enter decimal numbers only', 'SHORT');
    }
  }
  else if (type == 'text' && val != '') {
    let regex = new RegExp(/^[a-zA-Z0-9\s_.-]*$/);
    let isNUmeric = regex.test(val);
    if (!isNUmeric) {
      isValid = false;
      if (showMsg) notify('Please enter only characters and digits', 'SHORT');
    }
  } else if (type.toLowerCase() == 'qrtext' && val != '') {
    let regex = new RegExp(/^[a-zA-Z0-9@\s_.-\/:&$%#]*$/);
    let isNUmeric = regex.test(val);
    if (!isNUmeric) {
      isValid = false;
      if (showMsg) notify('Please enter only characters and digits', 'SHORT');
    }

  }

  return isValid;
}

// add new

export async function Add_metadataToImage(imgdata, TopText, BottomText, imgurl = '') {
  return new Promise(async (resolve, reject) => {
    console.log("start Add_metadataToImage RN: ", moment().format("MM/DD/YYYY HH:mm:ss"));
    if (ImageMarkText != null && imgurl != '') {
      let TextInfo = {
        "text": TopText, "BottomText": BottomText,
        "textStyle": {
          "TopTextfontSize": parseInt(imgdata.width * 0.06), "TopText_x": parseInt(imgdata.width * 0.01), "TopText_y": parseInt((imgdata.width * 0.06) + 50),
          "BottomTextfontSize": parseInt(imgdata.width * 0.03), "BottomText_x": parseInt(imgdata.width * 0.01), "BottomText_y": parseInt(imgdata.height + (imgdata.width * 0.03) + 30)
        }
      };
      let ImgInfo = { src: imgurl, height: imgdata.height, width: imgdata.width, ExtendedHeight: imgdata.ExtendedHeight };
      let url = await ImageMarkText.NativeImageMarkText(JSON.stringify(TextInfo), JSON.stringify(ImgInfo));

      console.log(url, "URL--->")

      console.log("end Add_metadataToImage RN: ", moment().format("MM/DD/YYYY HH:mm:ss"), url);
      if (url != null && typeof url == 'string') {
        // let fileparts= url.split("/");
        // let filename=fileparts[fileparts.length-1];
        // let destPath1=RNFS.DownloadDirectoryPath+"/"+filename;
        // RNFS.copyFile(url,destPath1);
        resolve({ success: true, "url": url });
      }
      else {
        resolve({ success: false, "error": "Cannot add metdata!" });
      }
    }
    else {
      console.log("end Add_metadataToImage RN: ", moment().format("MM/DD/YYYY HH:mm:ss"));
      resolve({ success: false, "error": "Native Module 'ImageMarkText' not found!" });
    }
  }).then((res) => {
    return res;
  }).catch((err) => {
    console.log("err:", err);
    return { success: false, error: err };
  })

}

export async function restore_ImageWithMetaData(data, imgdata) {
  let { destFilePath, imgurl, imgWidth, imgHeight, mark_text1, mark_text2 } = data
  // do not append metadata for ios
  if (Platform.OS == 'ios') {
    let fileparts = destFilePath.split("/");
    let filename = 'RES_' + fileparts[fileparts.length - 1];
    let destPath1 = RNFS.ExternalStorageDirectoryPath + "/" + filename;
    console.log('copy image from: ', destFilePath, ', to:', destPath1);
    RNFS.copyFile(destFilePath, destPath1);
    return true;
  }
  // add metadata
  // let res_metadata=await Add_metadataToImage(imgdata,mark_text1,mark_text2);
  // if(res_metadata.success && res_metadata.url!=null){
  // let imgWithMetaDataUrl=res_metadata.url;



  // cpoy to doownlload folder 

  // let fileparts= destFilePath.split("/");
  // let filename='ORG_'+fileparts[fileparts.length-1];
  // let destPath2=RNFS.DownloadDirectoryPath+"/"+filename;
  // console.log('copy org image from: ',imgurl,', to:',destPath2);
  // RNFS.copyFile(imgurl,destPath2);

  // resize file 
  let resize_res = await resizeImage(imgurl, imgWidth, imgHeight);
  if (resize_res.success) {
    // add metadata
    let resized_url = resize_res.uri != null && resize_res.uri != '' ? resize_res.uri.replace('file://', '') : '';
    let resized_imgD = resize_res.imgData != null ? resize_res.imgData : {};
    console.log("resized_url:", resized_url)
    // required larger height of image for landscape image 
    let ExtraSpace = 1.1; // portrait image  default 
    if (resized_imgD.width > resized_imgD.height) {
      // landscape image 
      ExtraSpace = 1.2
    }
    let resized_imgData = { uri: resized_url, width: parseInt(resized_imgD.width), height: parseInt(resized_imgD.height), ExtendedHeight: parseInt(resized_imgD.height * ExtraSpace) };

    let res_metadata = await Add_metadataToImage(resized_imgData, mark_text1, mark_text2, resized_url);

    console.log(res_metadata, "res_metadata-->")

    if (res_metadata.success && res_metadata.url != null) {
      let imgWithMetaDataUrl = res_metadata.url;

      let reducePixels_res = await reducePixels(imgWithMetaDataUrl, imgWidth, imgHeight);
      if (reducePixels_res.success) {
        await RNFS.unlink(imgurl); // delete local temp image created while we click an image
        await RNFS.unlink(resized_url); // delete local temp image created by first resize image function
        await RNFS.unlink(imgWithMetaDataUrl); // delete local temp image created by Add_metadataToImage function
        let isExists = await RNFS.exists(destFilePath); //delete dest file if exists
        if (isExists) { await RNFS.unlink(destFilePath); }
        return await RNFS.moveFile(reducePixels_res.uri, destFilePath).then((res) => {
          console.log('file restored to : ', destFilePath);
          // copy image in download folder
          // let fileparts= destFilePath.split("/");
          // let filename='RES_'+fileparts[fileparts.length-1];
          // let destPath1=RNFS.DownloadDirectoryPath+"/"+filename;
          // console.log('copy image from: ',destFilePath,', to:',destPath1);
          // RNFS.copyFile(destFilePath,destPath1);

          return true;
        }).catch((err) => {
          console.log("err:", err);
          return false;
        });
      }
      else {
        notify("Error while reducing pixels! " + (resize_res.error ? resize_res.error : ''));
        return false;
      }
    }
    else {
      notify("Error while adding metadata in image!" + (res_metadata.error ? res_metadata.error : ''));

      return true;
    }
  }
  else {
    notify("Error while resizing image! " + (resize_res.error ? resize_res.error : ''));
    return false;
  }

}

export const reducePixels = async (imgurl = '', imgWidth, imgHeight) => {

  if (imgurl != '') {
    // perform resize only whether imgWidth>1100 or imgHeight>1100
    if (imgWidth > 1100 || imgHeight > 1100) {
      // set max width and max height to 1100
      return await ImageResizer.createResizedImage(imgurl, 1100, 1100, 'JPEG', 40, 0, null, false, { onlyScaleDown: true, mode: 'contain' })
        .then(response => {
          let size = bytesToSize(response.size);
          console.log('after pixel reduce file size , w, h:', size, response.width, response.height);
          return { success: true, uri: response.uri };
        })
        .catch((err) => {
          console.log(err);
          return { success: false, error: err };
        });

    }
    else {
      return { success: true, uri: imgurl };
    }

  }
  else {
    return { success: false, imagenotfound: true };
  }
}

export const resizeImage = async (imgurl = '', imgWidth, imgHeight) => {
  if (imgurl != '') {
    return await ImageResizer.createResizedImage(imgurl, imgWidth, imgHeight, 'JPEG', 100, 0, null, false, { onlyScaleDown: true })
      .then(response => {
        let size = bytesToSize(response.size);
        console.log('resizeImage: reduced filesize:', size);
        return { success: true, uri: response.uri, imgData: response };
      })
      .catch((err) => {
        console.log(err);
        return { success: false, error: err };
      });
  }
  else {
    return { success: false, imagenotfound: true };
  }
}

export async function UpdateDistributorStatus(props, data, callback = () => { }) {
  let d1 = new Date();
  let today = moment(d1).format('MM/DD/YYYY');

  return new Promise((resolve, reject) => {

    if (data != null && data.UploadStatus != null && data.UploadStatus != '') {
      db.transaction(async function (txn) {

        let { StoreId, UploadStatus, tbname } = data;

        let q = `UPDATE ${tbname} SET UploadStatus='${UploadStatus}' WHERE DistributorId='${StoreId}' `;

        await txn.executeSql(q, [], async function (txn2, txnres2) {
          console.log('distributor status updated', UploadStatus,);
          callback(txnres2);
          resolve(true);
        }, function (Etxn, txnerr) { console.log(txnerr); resolve(false); });

      });
    }
    else {
      resolve(false);
    }
  }).then((val) => {
    return val;
  }).catch((err) => {
    console.log(err);
    return false;
  });


}

export const useOrientation = (width, height) => {
  // const dim=window;
  let isPortrait = height >= width;
  return isPortrait ? 'PORTRAIT' : 'LANDSCAPE';
}


export const useOrientation2 = (value) => {
  // const dim=window;
  let isPortrait = value == "LANDSCAPE-LEFT" || value == "LANDSCAPE-RIGHT";
  return isPortrait ? 'LANDSCAPE' : 'PORTRAIT';
}


// export async function fetchProjectConfig(managerAppConfig) {
//   try {
//     let loginInfo = await get_item('loginInfo');
//     const loginDetails = JSON.parse(loginInfo);

//     const configData =
//       typeof managerAppConfig === 'string'
//         ? JSON.parse(managerAppConfig)
//         : managerAppConfig;

//     const configArray = configData?.ManagerAppConfig ?? [];

//     const currentConfig = configArray.find(
//       item =>
//         item.Designation?.toLowerCase() ===
//         loginDetails?.Designation?.toLowerCase()
//     );

//     return currentConfig?.StorewisePJP ?? 0;
//   } catch (e) {
//     console.log('fetchProjectConfig error', e);
//     return 0;
//   }
// }

export async function fetchProjectConfig(managerAppConfig) {
  try {
    let loginInfo = await get_item('loginInfo');
    const loginDetails = JSON.parse(loginInfo);

    const configData =
      typeof managerAppConfig === 'string'
        ? JSON.parse(managerAppConfig)
        : managerAppConfig;

    const configArray = configData?.ManagerAppConfig ?? [];

    const currentConfig = configArray.find(
      item =>
        item.Designation?.toLowerCase() ===
        loginDetails?.Designation?.toLowerCase()
    );

    return {
      StorewisePJP: currentConfig?.StorewisePJP ?? false,
      StoreSearch: currentConfig?.StoreSearch ?? false,
    };
  } catch (e) {
    console.log('fetchProjectConfig error', e);
    return {
      StorewisePJP: false,
      StoreSearch: false,
    };
  }
}

   
