namespace ti_common.file.storage {
    'use strict';
    var fs = require('fs');
    var path = require('path');
    export class FileStorage {
        static $inject = ['$q'];

        constructor(private $q) { }

        saveFile(filePath: string, data: Content) {
            return this.$q((resolve, reject) => {
                fs.writeFile(filePath, data, (err) => {
                    if (err) {
                        reject(err);
                    } else {
                        resolve();
                    }
                });
            });
        }

        openFile(filePath: string) {
            return this.$q((resolve, reject) => {
                fs.readFile(filePath, 'utf-8', (err, data) => {
                    if (err) {
                        reject(err);
                    } else {
                        resolve(data);
                    }
                });
            });
        }

        fileExists(filePath: string) {
            return this.$q((resolve, reject) => {
                fs.stat(filePath, (err, data) => {
                    if (err == null) {
                        resolve(true);
                    } else if (err.code === 'ENOENT') {
                        resolve(false);
                    } else {
                        reject(err.code);
                    }
                });
            });
        }

        getAppDataDirectory() {
            let isWin = process.platform.indexOf("win") === 0;
            let getLocalAppData = isWin ? (process.env.LOCALAPPDATA || process.env.USERPROFILE) : (process.env.HOME);
            let tiFolderName = isWin ? 'Texas Instruments' : '.ti';
            let uniflashFolderName = 'uniflash';
            return this.$q((resolve) => {
                let tiDir = path.join(getLocalAppData, tiFolderName);
                if (!fs.existsSync(tiDir)) {
                    fs.mkdirSync(tiDir);
                }
                let appDir = path.join(tiDir, uniflashFolderName);
                if (!fs.existsSync(appDir)) {
                    fs.mkdirSync(appDir);
                }
                resolve(appDir);
            });
        }
    }

    angular.module('ti_common').service('ticFileStorage', FileStorage);
}