#!/usr/bin/env python

import os
import urllib
import json

from dm.common.utility.encoder import Encoder
from dm.common.exceptions.dmException import DmException
from dm.common.exceptions.invalidRequest import InvalidRequest
from dm.common.objects.fileMetadata import FileMetadata
from catRestApi import CatRestApi

class FileRestApi(CatRestApi):
    
    def __init__(self, username=None, password=None, host=None, port=None, protocol=None):
        CatRestApi.__init__(self, username, password, host, port, protocol)

    @CatRestApi.execute
    def addExperimentFile(self, fileInfo):
        experimentName = fileInfo.get('experimentName')
        if not experimentName:
            raise InvalidRequest('File metadata must contain experimentName key.')
        fileName = fileInfo.get('name')
        if not fileName:
            raise InvalidRequest('File metadata must contain name key.')
        url = '%s/filesByExperiment/%s/%s' % (self.getContextRoot(), experimentName, fileName)
        url += '?fileInfo=%s' % (Encoder.encode(json.dumps(fileInfo)))
        responseData = self.sendRequest(url=url, method='POST')
        return FileMetadata(responseData)

    @CatRestApi.execute
    def updateExperimentFile(self, fileInfo):
        experimentName = fileInfo.get('experimentName')
        if not experimentName:
            raise InvalidRequest('File metadata must contain experimentName key.')
        fileName = fileInfo.get('name')
        if not fileName:
            raise InvalidRequest('File metadata must contain name key.')
        url = '%s/filesByExperiment/%s/%s' % (self.getContextRoot(), experimentName, fileName)
        url += '?fileInfo=%s' % (Encoder.encode(json.dumps(fileInfo)))
        responseData = self.sendRequest(url=url, method='PUT')
        return FileMetadata(responseData)

    @CatRestApi.execute
    def updateFileById(self, fileInfo):
        id = fileInfo.get('id')
        if not id:
            raise InvalidRequest('File metadata must contain id key.')
        url = '%s/files/%s' % (self.getContextRoot(), id)
        url += '?fileInfo=%s' % (Encoder.encode(json.dumps(fileInfo)))
        responseData = self.sendRequest(url=url, method='PUT')
        return FileMetadata(responseData)

    @CatRestApi.execute
    def getFiles(self, queryDict={}):
        url = '%s/files' % (self.getContextRoot())
        url += '?queryDict=%s' % (Encoder.encode(json.dumps(queryDict)))
        responseData = self.sendRequest(url=url, method='GET')
        return self.toDmObjectList(responseData, FileMetadata)

    @CatRestApi.execute
    def getExperimentFiles(self, experimentName, queryDict={}):
        if not experimentName:
            raise InvalidRequest('Invalid experiment name provided.')
        url = '%s/filesByExperiment/%s' % (self.getContextRoot(), experimentName)
        url += '?queryDict=%s' % (Encoder.encode(json.dumps(queryDict)))
        responseData = self.sendRequest(url=url, method='GET')
        return self.toDmObjectList(responseData, FileMetadata)

    @CatRestApi.execute
    def getFileById(self, id):
        if not id:
            raise InvalidRequest('Invalid file id provided.')
        url = '%s/files/%s' % (self.getContextRoot(), id)
        responseData = self.sendRequest(url=url, method='GET')
        return FileMetadata(responseData)

    @CatRestApi.execute
    def getExperimentFile(self, experimentName, fileName):
        if not experimentName:
            raise InvalidRequest('Invalid experiment name provided.')
        if not fileName:
            raise InvalidRequest('Invalid file name provided.')
        url = '%s/filesByExperiment/%s/%s' % (self.getContextRoot(), experimentName, fileName)
        responseData = self.sendRequest(url=url, method='GET')
        return FileMetadata(responseData)

#######################################################################
# Testing.

if __name__ == '__main__':
    api = FileRestApi()
    print api.getFiles()
    print api.getFileById('556de0059e058b0ef4c4413b')
    print api.getFileByName('xyz-001')

    import time
    t = long(time.time())
    fileInfo = {
        'name' : 'sv-%s' % t,
        'experimentName' : 'exp1',
        'power' : 12,
        'powerUnits' : 'kW',
        'force' : 15,
        'forceUnits' : 'N',
        'cKey' : {'a' : 1, 'b' : 'B', 'c' : 2.2},
    }
    fileMetadata = api.addFileByName(fileInfo)

    print '\nADDED FILE:\n', fileMetadata
 
    fileInfo['updateKey'] = 'here is desc'
    fileMetadata = api.updateFileByName(fileInfo)
    print '\nUPDATED FILE:\n', fileMetadata

    fileInfo['updateKey2'] = 'new desc'
    fileInfo['id'] = fileMetadata.get('id')
    fileMetadata = api.updateFileById(fileInfo)
    print '\nUPDATED FILE:\n', fileMetadata

    queryDict = { 'experimentName' : 'exp2' }
    print '\nQUERY FILES:\n', api.getFiles(queryDict=queryDict)