const {queryDb} = require("./db");
const logger = require('./logger');
const userAg = require('useragent');
const moment = require('moment');
const getURLParameters = require('./urlParameters');

async function isBotTraffic(visitorIp, url) {
  console.log('url: ', url);

  let urlIncludesGClId = false;
  let blockReason = '';
  let data = {
    initialUrl: url,
    isBot: true,
    blockReason: '',
    isGoogle: 0,
  };

  if (url.includes('?gclid')) {
    urlIncludesGClId = true;
    data.isGoogle = 1;
    console.log('The checkUrl CONTAINS "?gclid"');
  } else {
    console.log('The checkUrl does NOT contain "?gclid"');
  }

  try { //checking user agent
    const today = moment().format('YYYY-MM-DD');
    const searchQuery = `SELECT * FROM Logs WHERE ip = '${visitorIp}' AND DATE(date) = '${today}' AND url LIKE '%${url}%'`;
    const rows = await queryDb(searchQuery);

    if(rows.length === 0){
        data.blockReason = 'Not blocked, no logs found';
        data.blockIP = false;
    } else if(rows.length >= 1 && urlIncludesGClId){
        data.blockReason = 'Accessed today 2+ times the same page with gclid';
        console.log(`IP found : ${visitorIp}`);
        data.blockIP = true;
    } else if(rows.length >= 3){
        data.blockReason = 'Accessed today 4+ times the same page without gclid';
        console.log(`IP found : ${visitorIp}`);
        data.blockIP = true;
    } else {
        data.blockReason = 'Not blocked, no conditions met';
        data.blockIP = false;
    }
  } catch (error) {
    logger.error('Error selecting data from db:', error);
    console.error('Error selecting data from db:', error);
  }

  try { //checking if multiple entries from the same ip
    const today = moment().format('YYYY-MM-DD');
    const searchQuery = `SELECT * FROM Logs WHERE ip = '${visitorIp}' AND DATE(date) = '${today}' AND url LIKE '%${url}%'`;
    const rows = await queryDb(searchQuery);

    if(rows.length === 0){
        data.blockReason = 'Not blocked, no logs found';
        data.blockIP = false;
    } else if(rows.length >= 1 && urlIncludesGClId){
        data.blockReason = 'Accessed today 2+ times the same page with gclid';
        console.log(`IP found : ${visitorIp}`);
        data.blockIP = true;
    // } else if(rows.length >= 3){
    //     data.blockReason = 'Accessed today 4+ times the same page without gclid';
    //     console.log(`IP found : ${visitorIp}`);
    //     data.blockIP = true;
    } else {
        data.blockReason = 'Not blocked, no conditions met';
        data.blockIP = false;
    }
  } catch (error) {
    logger.error('Error selecting data from db:', error);
    console.error('Error selecting data from db:', error);
  }


  return data;
}

async function getCurrDateTime(type) {
  const currentDate = new Date();
  if(type === 'date'){
    const year = currentDate.getFullYear();
    const month = currentDate.getMonth() + 1; // Months are 0-indexed, so add 1
    const day = currentDate.getDate();
    const formattedDate = `${year}-${month}-${day}`;
    // console.log('Current Date:', formattedDate);
    return formattedDate;
  } else {
    const hours = currentDate.getHours();
    const minutes = currentDate.getMinutes();
    const seconds = currentDate.getSeconds();
    const formattedTime = `${hours}:${minutes}:${seconds}`;
    // console.log('Current Time:', formattedTime);
    return formattedTime;
  }
}

async function getUrlPage(url) {
  let data = {
    page: '',
    postcode: '',
    location: '',
  };

  if(url.includes('/locations/')){
    data.location = url.split('/')[2].split('?')[0];
    console.log(data.location);
  } else {
    data.page = url.split('/')[1].split('?')[0];
    if(typeof data.page === 'undefined' || !data.page)
      data.page = 'home';
    console.log(data.page);
  }
  
  return data;
}

module.exports = async function dbClickLogger(req, isVpn) {
  let reCScore = -1;

  const ipAddress = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
//   console.log(ipAddress);
  const visitorIp = ipAddress.split(',')[0].trim();
  const userAgentSource = req.useragent.source;
  const userAgentString = req.headers['user-agent'];
  // const isVPN = /vpn|proxy|tor/i.test(userAgentSource);
  // logger.info('ip adress: ', ipAddress);

  if (req.url.includes('/img/') || req.url.includes('/favicon.ico')) {
    // console.log('req.url contains "/img/"');
    return;
  } 

  passedUrl = decodeURIComponent(req.url.split('=')[1].split('&')[0]);
  position = decodeURIComponent(req.url.split('=')[2]);
  // console.log('passedUrl: ', passedUrl);
  // console.log('position: ', position);

  const parameters = await getURLParameters('https://24hrslocksmith.co.uk' + passedUrl);
  campaignParam = parameters.find(param => param.name === 'campaign')?.value;
  adGroupParam = parameters.find(param => param.name === 'adgroup')?.value;
  campaignIdParam = parameters.find(param => param.name === 'campaignid')?.value;
  adGroupIdParam = parameters.find(param => param.name === 'adgroupid')?.value;
  keywordParam = parameters.find(param => param.name === 'keyword')?.value;
  deviceParam = parameters.find(param => param.name === 'device')?.value;
  adPositionParam = parameters.find(param => param.name === 'adposition')?.value;

  pageName = await getUrlPage(passedUrl);

  const page = pageName.page === "null" ? null : pageName.page;
  const postcode = pageName.postcode === "null" ? null : pageName.postcode;
  const location = pageName.location === "null" ? null : pageName.location;

  const isBotData = await isBotTraffic(visitorIp, passedUrl);

  let isBlockedIp = 0;
  let ipBlockedNow = 0;

    try {
      const dontDuplicateQuery = `SELECT * FROM BlockedIPs WHERE ip = '${visitorIp}';`;
      const isIpInBlocked = await queryDb(dontDuplicateQuery);

      if(isIpInBlocked.length !== 0){
        console.log(`Ip is in BlockedIPs: ${visitorIp}`);
        isBlockedIp = 1;
      }

    } catch (error) {
      // logger.error('Error querying data:', error);
      console.error('Error querying data:', error);
    }

  dateOnly = await getCurrDateTime('date');
  hourOnly = await getCurrDateTime('time');

  try {
    // console.log('url: ', isBotData.initialUrl);
    const q = `INSERT INTO ClickLogs (ip, url, campaign, adgroup, campaignid, adgroupid, keyword, device, adposition, page, postcode, location, dateOnly, hourOnly, GoogleSource, btnPosition, isBlockedIp, recaptchaScore, user_agent, user_agent_source, browser, version, os, platform, geoIp, isYaBrowser, isAuthoritative, isMobile, isMobileNative, isTablet, isiPad, isiPod, isiPhone, isiPhoneNative, isAndroid, isAndroidNative, isBlackberry, isOpera, isIE, isEdge, isIECompatibilityMode, isSafari, isFirefox, isWebkit, isChrome, isKonqueror, isOmniWeb, isSeaMonkey, isFlock, isAmaya, isPhantomJS, isEpiphany, isDesktop, isWindows, isLinux, isLinux64, isMac, isChromeOS, isBada, isSamsung, isRaspberry, is_bot, isCurl, isAndroidTablet, isWinJs, isKindleFire, isSilk, isCaptive, isSmartTV, isUC, isFacebook, isAlamoFire, isElectron, silkAccelerated, isWechat) VALUES ('${visitorIp}','${passedUrl}','${campaignParam}','${adGroupParam}','${campaignIdParam}','${adGroupIdParam}','${keywordParam}','${deviceParam}','${adPositionParam}','${page}','${postcode}','${location}','${dateOnly}','${hourOnly}','${isBotData.isGoogle}','${position}','${isBlockedIp}','${reCScore}','${JSON.stringify(req.useragent)}', '${userAgentSource}', '${req.useragent.browser}', '${req.useragent.version}', '${req.useragent.os}', '${req.useragent.platform}', '${JSON.stringify(req.useragent.geoIp)}', ${req.useragent.isYaBrowser}, ${req.useragent.isAuthoritative}, ${req.useragent.isMobile}, ${req.useragent.isMobileNative}, ${req.useragent.isTablet}, ${req.useragent.isiPad}, ${req.useragent.isiPod}, ${req.useragent.isiPhone}, ${req.useragent.isiPhoneNative}, ${req.useragent.isAndroid}, ${req.useragent.isAndroidNative}, ${req.useragent.isBlackberry}, ${req.useragent.isOpera}, ${req.useragent.isIE}, ${req.useragent.isEdge}, ${req.useragent.isIECompatibilityMode}, ${req.useragent.isSafari}, ${req.useragent.isFirefox}, ${req.useragent.isWebkit}, ${req.useragent.isChrome}, ${req.useragent.isKonqueror}, ${req.useragent.isOmniWeb}, ${req.useragent.isSeaMonkey}, ${req.useragent.isFlock}, ${req.useragent.isAmaya}, ${req.useragent.isPhantomJS}, ${req.useragent.isEpiphany}, ${req.useragent.isDesktop}, ${req.useragent.isWindows}, ${req.useragent.isLinux}, ${req.useragent.isLinux64}, ${req.useragent.isMac}, ${req.useragent.isChromeOS}, ${req.useragent.isBada}, ${req.useragent.isSamsung}, ${req.useragent.isRaspberry}, ${req.useragent.isBot}, ${req.useragent.isCurl}, ${req.useragent.isAndroidTablet}, ${req.useragent.isWinJs}, ${req.useragent.isKindleFire}, ${req.useragent.isSilk}, ${req.useragent.isCaptive}, ${req.useragent.isSmartTV}, ${req.useragent.isUC}, ${req.useragent.isFacebook}, ${req.useragent.isAlamoFire}, ${req.useragent.isElectron}, ${req.useragent.silkAccelerated}, ${req.useragent.isWechat});`;
    const result = await queryDb(q);
    logger.info('Inserted ip in Logss');
  } catch (error) {
    logger.error('Error inserting data', error);
    console.error('Error inserting data:', error);
  }
};