import rewiremock from 'rewiremock';
import '../../../mocks/electron';

import { expect } from 'chai';
import fs from 'fs-extra';
import 'mocha';
import path from 'path';
import { load, save, StoreKeys } from '../../../src/main/services/store';

const storeDirectory = path.resolve('store');

describe('Store Service', function() {
  this.timeout(10000);

  before(() => {
    rewiremock.enable();
  });

  after(() => {
    rewiremock.disable();
  });

  beforeEach(() => {
    if (fs.existsSync(storeDirectory)) {
      fs.removeSync(storeDirectory);
    }
  });

  it('creates a store directory', () => {
    return save(StoreKeys.COOKIES, { some: 'data' }).then(() => {
      expect(fs.existsSync(storeDirectory)).to.be.true;
    });
  });

  it('loads saved data', () => {
    const testData: any = {
      something: 'gaga',
      somethingElse: 0,
      deepObject: {
        somthingAsWell: true,
        somethingNotInJson: undefined,
        someArray: [
          'hui',
          {
            g: 'h',
          },
        ],
      },
    };
    const expectedJson = JSON.stringify(testData);
    return save(StoreKeys.COOKIES, testData)
      .then(() => {
        return load(StoreKeys.COOKIES);
      })
      .then((data) => {
        expect(JSON.stringify(data)).to.equal(expectedJson, 'store does not save and load data correctly');
        return load(StoreKeys.COOKIES);
      })
      .then((data) => {
        expect(JSON.stringify(data)).to.equal(expectedJson, 'store does load data correctly when loaded twice');
      });
  });

  it('handles a deleted store directory', () => {
    const testData = 'test_data';
    return save(StoreKeys.COOKIES, testData)
      .then(() => {
        fs.removeSync(storeDirectory);
        return load(StoreKeys.COOKIES);
      })
      .then((data) => {
        expect(data).to.equal(testData, 'store does not load when store directory is deleted');
      });
  });

  it('handles a deleted store file', () => {
    const testData = 'test_data';
    return save(StoreKeys.COOKIES, testData)
      .then(() => {
        fs.readdirSync(storeDirectory).forEach((file) => {
          fs.unlinkSync(path.resolve(storeDirectory, file));
        });
        return load(StoreKeys.COOKIES);
      })
      .then((data) => {
        expect(data).to.equal(testData, 'store does not load when store files are deleted');
      });
  });
});
