import path from 'node:path';
import os from 'node:os';
import { existsSync, mkdirSync, readFileSync } from 'node:fs';
import DigestFetch from 'digest-fetch';
import type { Config, User } from './types.ts';

const getWorkDirectory = () => {

  const workDirectoryPath = path.join(os.homedir(), 'Documents', 'netgym', 'hikvision');

  if (!existsSync(workDirectoryPath)) 
    mkdirSync(workDirectoryPath, { recursive: true });

  return workDirectoryPath;

}

const loadConfig = (): Config => {

  try {

    return {
      ip: '192.168.18.82',
      user: 'admin',
      password: 'Netgym2025*'
    }

    // // Get config file path
    // const configFilePath = path.join(getWorkDirectory(), 'config.json');

    // // Get config file content
    // const fileContent = readFileSync(configFilePath, 'utf8');

    // // return config
    // return JSON.parse(fileContent);

  }
  catch(error) {
    console.error('Error in credentials');
    throw new Error();
  }

}

const addUser = async (user: User) => {

  const response: Response = await digestClient.fetch('http://192.168.18.82/ISAPI/AccessControl/UserInfo/Record?format=json', {
    method: 'POST',
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({
      "UserInfo": {
        "RightPlan": [
          {
            "doorNo": 1,
            "planTemplateNo": "1"
          }
        ],
        "Valid": {
          "beginTime": "2025-01-01T00:00:00",
          "enable": true,
          "endTime": "2027-12-31T23:59:59"
        },
        "doorRight": "1",
        "employeeNo": user.id,
        "name": user.name,
        "userType": "normal"
      }
    })
  })

  if (response.status === 401) {
    console.log(`401 - ${user.id}`)
    return await addUser(user)
  }

  console.log(user.id)
  return response.json();

}

const addFace = async (user: User) => {

  const fileBuffer = readFileSync(path.join('.', 'data', 'images', `${user.id}.jpg`));
  const fileBlob = new Blob([fileBuffer], { type: 'image/jpeg' });

  const formdata = new FormData();
  formdata.append("FaceDataRecord", JSON.stringify({
    "faceLibType": "blackFD",
    "FDID": "1",
    "FPID": `${user.id}`,
    "name": `${user.name}`
  }));
  formdata.append("img", fileBlob);

  const response: Response = await digestClient.fetch('http://192.168.18.82/ISAPI/Intelligent/FDLib/FaceDataRecord?format=json', {
    method: 'POST',
    body: formdata
  })

  if (response.status === 401) {
    console.log(`401 - ${user.id}`)
    return await addFace(user)
  }

  console.log(user.id)
  return response.json();

}

const importUsersInformation = async () => {

  const file = readFileSync(path.join('.', 'data', 'users.json'), 'utf-8');

  const users: User[] = JSON.parse(file);

  let usersSuccessCount = 0;
  let usersErrors: any[] = [];

  for (const user of users) {
    const result: any = await addUser(user);
    if (result.statusString === 'OK') usersSuccessCount++;
    else usersErrors.push({ user, result })
  }

  console.log(`${usersSuccessCount} users imported`)
  console.log(`${usersErrors.length} users with errors`)
  console.log(usersErrors)

  let imagesSuccessCount = 0;
  let imagesErrors: any[] = [];

  for (const user of users) {
    if (user.imageUrl) {
      const result: any = await addFace(user);
      if (result.statusString === 'OK') imagesSuccessCount++;
      else imagesErrors.push({ user, result })
    }
  }

  console.log(`${imagesSuccessCount} users imported`)
  console.log(`${imagesErrors.length} users with errors`)
  console.log(imagesErrors)

}

const config = loadConfig();
const digestClient = new DigestFetch(config.user, config.password);
importUsersInformation();

// console.log(await addFace({ id: "10", name: "", imageUrl: "" }))