# -*- coding: utf-8 -*-
from __future__ import division
import json
import os
import sys
import base64
import struct
import pandas as pd
import re
import zlib


def read_txt():
    """
    read txt_file
    """
    meter_number = []
    file_object = open(r'C:\Users\harry-shen\Desktop\1511375965')
    strs = file_object.readlines()
    file_object.close()
    write_file = open(r'C:\Users\harry-shen\Desktop\1511375965\data.csv','w')
    for str in strs:
        if str.split()[0] not in meter_number:
            meter_number.append(str.split()[0])
            write_file.write('%s\n'%str.split()[0])
    write_file.close()


def read_json_file(file_name):
    '''just read config of poll'''
    data = None
    if os.path.exists(file_name):
        f = open(file_name, 'r')
        # data = json.load(f)
        data = f.read()
        # data=eval(data)
        # data=data['data']
        # data = base64.b64decode(data)
        # data = zlib.decompress(data)

        dev_data = json.loads(data)
        f.close()
        return dev_data
    else:
        return None


def data_transfer(data):
    scope_data = ""
    decoded_data = ""
    list_data = []
    scope_data = data["data"]

    decoded_data = base64.b64decode(scope_data)
    # list_data = list(struct.unpack("<4800H", decoded_data))

    list_data = list(struct.unpack("<2400H", decoded_data))
    return list_data
    
def pb620_d2a(data, type='vol'):
    """
    PB620装置数模转换子程序
    """
    enable = True
    if enable:
        if type == 'vol':
            coef = 216/(44*10)
        else:
            coef = 1/(8.2*4.7*2*2.4)
        tdata = []
        for dig_data in data:
          temp_data = (dig_data*0.000806 - 1.8)*1000*coef
          tdata.append(temp_data)
    else:
        tdata = data
    return tdata

def cal_delt(data, value_limit):
    delt_count = 0
    index_seg = 0
    index_loc = 0
    npoint = 80
    for k in range(npoint, len(data)):
        delt_temp = (data[k] - data[k-npoint])
        if abs(delt_temp) > value_limit:
            delt_count += 1
        else:
            delt_count = 0
        if delt_count >= 3:
            curPP = max(data[k-3:k-3+npoint]) - min(data[k-3:k-3+npoint])
            lastPP = max(data[k-3-npoint:k-3]) - min(data[k-3-npoint:k-3])
            if abs(curPP - lastPP) > 0.1*lastPP:
                index_seg = int(k / (10*npoint))
                index_loc = k % (10*npoint)
                if index_loc > 160:
                    index_loc = index_loc - 160
                else:
                    index_seg = index_seg - 1
                    index_loc = 640 + index_loc
                break
    return delt_count, index_seg, index_loc
    
def read_excel(file_dir):
    """
    读取excel 程序
    """
    df = pd.read_excel(file_dir)
    return df




