import os
from os import listdir
from os.path import isfile, join
from flask import json, abort

from app.entity.strategy.StrategyCalculatorDataBean import StrategyCalculatorDataBean
from app.processor.strategy.StrategyCalculatorDataBeanBuilder import StrategyCalculatorDataBeanBuilder
from app.entity.ConstantValue import *

from app.resource.CustomerJSONEncoder import *



class StrategyDataLoader:
    @staticmethod
    def getStrategies(userId):
        return StrategyDataLoader.getStrategiesWithPrefix(userId, None, -1)

    @staticmethod
    def getStrategiesBySize(userId, size):
        return StrategyDataLoader.getStrategiesWithPrefix(userId, None, size)

    @staticmethod
    def getStrategiesWithPrefix(userId, name, size):
        if userId is None:
            userId = 'guest'
        
        appPath = os.path.dirname(__file__) + '/../../..'
        mypath = appPath + '/configure/strategy/' + userId + '/'
        
        strategyNames = []
        
        if os.path.exists(mypath):
            onlyfiles = [ f for f in listdir(mypath) if isfile(join(mypath,f)) ]
            for fileName in onlyfiles:
                strategyNames.append(fileName[:-5])
        strategyNames.sort()
        
        if size <= 0:
            pass
        elif name is None or len(name) == 0:
            strategyNames = strategyNames[:size]
        else:
            strategyNames = [elem for elem in strategyNames if str(elem).lower().startswith(name.lower())]
            strategyNames = strategyNames[:size]
        
        return {userId: strategyNames}

    @staticmethod
    def load(userId, strategyName):
        appPath = os.path.dirname(__file__) + '/../../..'
        fileName = appPath + '/configure/strategy/' + userId + '/' + strategyName + '.data'
        
        if not StrategyDataLoader.check_exist(fileName):
            abort(500)  
        
        with open(fileName, 'r+') as inFile:
            loadData = json.load(inFile)
            
        return StrategyCalculatorDataBeanBuilder.build(loadData)

    
    @staticmethod
    def save(userId, strategyName, dataValue):
        appPath = os.path.dirname(__file__) + '/../../..'
        fileName = appPath + '/configure/strategy/' + userId + '/' + strategyName + '.data'
        
        StrategyDataLoader.ensure_dir(fileName)
        with open(fileName, 'w+') as outFile:
            json.dump(dataValue, outFile, cls=CustomerJSONEncoder)
    
    @staticmethod
    def delete(userId, strategyName):
        if not StrategyDataLoader.isExist(userId, strategyName):
            abort(500)
        
        strategyCalculatorDataBean = StrategyDataLoader.load(userId, strategyName)
            
        appPath = os.path.dirname(__file__) + '/../../..'
        fileName = appPath + '/configure/strategy/' + userId + '/' + strategyName + '.data'
        
        os.remove(fileName)
        
        return strategyCalculatorDataBean
   
    
    @staticmethod
    def isExist(userId, strategyName):
        appPath = os.path.dirname(__file__) + '/../../..'
        fileName = appPath + '/configure/strategy/' + userId + '/' + strategyName + '.data'
        
        if StrategyDataLoader.check_exist(fileName):
            return True
        
        return False 
    
    @staticmethod   
    def ensure_dir(f):
        d = os.path.dirname(f)
        if not os.path.exists(d):
            os.makedirs(d) 
            
    @staticmethod   
    def check_exist(f):
        if os.path.isfile(f):
            return True
        else:
            return False