#! /usr/bin/env python
# -*- coding: utf-8 -*-
'''
Created on 2022.08

@author: laok
@copyright: Apache License, Version 2.0
'''
from collections import OrderedDict
# ===============================================================================
#                                                                                
# ===============================================================================
__all__ = [ 'file_read_text', 'file_read_bin', 
            'file_write_text', 'file_write_bin',
            'file_read_lines', 'file_write_lines',
            'ClsIdx']

def file_read_text(fname, encoding='utf8'):
    with open(fname, mode='r', encoding=encoding) as f:
        return f.read()

def file_write_text(fname, text, encoding='utf8'):
    with open(fname, mode='w', encoding=encoding) as f:
        f.write(text)

def file_read_lines(fname, encoding='utf8', strip = True):
    with open(fname, mode='r', encoding=encoding) as f:
        line = f.readline()
        if strip:
            line = line.strip()
        yield line

def file_write_lines(fname, lines, encoding='utf8', line_append='\n'):
    with open(fname, mode='w', encoding=encoding) as f:
        for line in lines:
            f.write(line + line_append)

def file_read_bin(fname):
    with open(fname, mode='rb') as f:
        return f.read()

def file_write_bin(fname, data):
    with open(fname, mode='wb') as f:
        f.write(data)


class ClsIdx:
    def __init__(self, cls_file = None):
        self.cls_data_ = OrderedDict()
        if cls_file:
            self.setClsFile(cls_file)

    def setClsFile(self, cls_file):
        with open(cls_file) as f:
            for i,line in enumerate(f):
                self.cls_data_[i] = line.strip()
        return self

    def getName(self, idx):
        _idx = int(idx)
        return self.cls_data_.get(_idx, '')

    def getIndex(self, name):
        if name == None or name == '':
            return -1
        for _idx, _name in self.cls_data_.items():
            if name in _name:
                return _idx
        return -1

    def show(self):
        for k,v in self.cls_data_.items():
            print(f'{k}={v}')
