import xml.etree.ElementTree as ET
import requests

class Kipris_API:
    def __init__(self, apikey=None):
        self.url = 'http://kipo-api.kipi.or.kr/openapi/service/trademarkInfoSearchService/getWordSearch'
        self.apikey = apikey
        self.results = []

    def fetch_and_decode(self, params):
        # API 요청 및 응답 받기
        try:
            response = requests.get(self.url, params=params)
            decoded_data = response.content.decode('utf-8')
            return decoded_data
        except Exception as e:
            print(f"키프리스 요청 중 에러발생 : {e}")

    def parse_xml(self, xml_data, status):
        # XML 데이터 파싱
        root = ET.fromstring(xml_data)
        total_items = 0
        status_registered = 0
        status_published = 0
        
        # 'body/items/item' 경로에 맞춰 'item' 태그를 순회하면서 필요한 데이터 추출
        for item in root.findall('.//body/items/item'):
            total_items += 1
            application_status = item.find('applicationStatus').text if item.find('applicationStatus') is not None else None

            # 각 상태의 개수를 카운트
            if application_status == "등록":
                status_registered += 1
            if application_status == "공개":
                status_published += 1

            if application_status in ["등록", "공개"]:
                result = {
                    "index_no": item.find('indexNo').text if item.find('indexNo') is not None else None,
                    "application_number": item.find('applicationNumber').text if item.find('applicationNumber') is not None else None,
                    "application_date": item.find('applicationDate').text if item.find('applicationDate') is not None else None,
                    "publication_number": item.find('publicationNumber').text if item.find('publicationNumber') is not None else None,
                    "publication_date": item.find('publicationDate').text if item.find('publicationDate') is not None else None,
                    "registration_date": item.find('registrationDate').text if item.find('registrationDate') is not None else None,
                    "registration_number": item.find('registrationNumber').text if item.find('registrationNumber') is not None else None,
                    "applicant_name": item.find('applicantName').text if item.find('applicantName') is not None else None,
                    "agent_name": item.find('agentName').text if item.find('agentName') is not None else None,
                    "title": item.find('title').text if item.find('title') is not None else None,
                    "drawing_url": item.find('drawing').text if item.find('drawing') is not None else None,
                    "big_drawing_url": item.find('bigDrawing').text if item.find('bigDrawing') is not None else None,
                    "full_text": item.find('fullText').text if item.find('fullText') is not None else None,
                    "application_status": application_status,
                    "classification_code": item.find('classificationCode').text if item.find('classificationCode') is not None else None
                }
                self.results.append(result)

        # 상태 개수와 총 아이템 개수 출력
        print(f"검색된 item 총 개수: {total_items}")
        print(f"등록 상태인 item 개수: {status_registered}")
        print(f"공개 상태인 item 개수: {status_published}")

    def get_results(self):
        return self.results

    def run(self, keyword, status):
        params = {
            'serviceKey': self.apikey,
            'searchString': keyword,
            'searchRecentYear': '0',
            'title': '',
            'fullText': '',
            'drawing': '',
            'bigDrawing': ''
        }
        xml_data = self.fetch_and_decode(params)
        self.parse_xml(xml_data, status)
        return self.get_results()

    def close_Kipris(self):
        pass