# -*- coding:utf-8 -*-

'''
project_name
project_branch
app_code
project_url
operator_email
app_version
'''
import json
import os
import urllib2


class Request():
    def post(self, url, data, headers={}):
        request = urllib2.Request(url, headers=headers, data=data)
        response = urllib2.urlopen(request)
        return response

    def post_json(self, url, data):
        headers = {'Content-Type': 'application/json'}
        return self.post(url, data, headers)


class SyncReleaseInfoToDB(object):

    def __init__(self):
        self.info_dict = self.get_env()

    def run(self):
        '''
        执行同步
        :return:
        '''
        # log_db_connection_str = os.getenv('LOG_DB_CONNECTION_STR', '')
        # if not log_db_connection_str.strip():
        #     print('未配置数据库连接字符串LOG_DB_CONNECTION_STR，退出程序...')
        #     return

        try:
            log_data_dict = {
                "type": "pbAPPUpgradeReleaseHistory",
                "param": "",
                "data": {
                    "pbAPPUpgradeReleaseHistory": [self.info_dict]
                }
            }

            log_data_str = json.dumps(log_data_dict)

            gql_url = "http://" + os.getenv('HSGQL_URL', '47.110.145.204:8129') + "/sql_gql/save/?is_logger=false"

            response = Request().post_json(gql_url, data=log_data_str)
            rs = response.read()
            print(rs)
        except Exception as e:
            print("同步报错:{}".format(str(e)))

    def get_env(self):
        '''
        获取所有环境变量
        :return:
        '''
        app_code = os.getenv('APP_CODE', '')
        project_branch = os.getenv('CI_COMMIT_REF_NAME', '')
        app_version = os.getenv('APP_VERSION', project_branch)
        project_url = os.getenv('CI_PROJECT_URL', '')
        project_name = os.getenv('CI_PROJECT_NAME', '')
        operator_email = os.getenv('GITLAB_USER_EMAIL', '')
        app_name = os.getenv('APP_NAME', '')
        ci_pipeline_url = os.getenv('CI_PIPELINE_URL', '')
        operator = os.getenv('GITLAB_USER_NAME', '')
        commit_message = os.getenv('CI_COMMIT_MESSAGE', '')

        info_dict = {
            "_action": 1
            , "app_code": app_code
            , "app_version": app_version
            , "project_branch": project_branch
            , "project_url": project_url
            , "project_name": project_name
            , "operator_email": operator_email
            , "app_name": app_name
            , "operator": operator
            , "ci_pipeline_url": ci_pipeline_url
            , "commit_message": commit_message
        }

        return info_dict


if __name__ == "__main__":
    SyncReleaseInfoToDB().run()
