from http.server import BaseHTTPRequestHandler, HTTPServer
import xml.etree.ElementTree as ET
import os
import json

HOST_NAME = 'localhost'
PORT_NUMBER = 8000

class MyHandler(BaseHTTPRequestHandler):
    def do_POST(self):
        if self.path == '/save_user':
            self.handle_registration()
        elif self.path == '/login':
            self.handle_login()
        elif self.path == '/get_user':
            self.handle_get_user()
        elif self.path == '/saves_user':
            self.handle_update_user()
        else:
            self.send_error(404, 'Not Found')

    def handle_registration(self):
        # Получаем XML-данные из запроса
        content_length = int(self.headers['Content-Length'])
        xml_data = self.rfile.read(content_length).decode('utf-8')

        # Парсим XML-данные
        root = ET.fromstring(xml_data)

        # Извлекаем информацию из XML
        name = root.find('name').text
        phone = root.find('phone').text
        email = root.find('email').text
        code = root.find('code').text
        password = root.find('password').text

        # Сохраняем данные в файл registrations.xml
        with open('registrations.xml', 'a', encoding='utf-8') as f:
            f.write(f"""
                <user>
                    <name>{name}</name>
                    <phone>{phone}</phone>
                    <email>{email}</email>
                    <code>{code}</code>
                    <password>{password}</password>
                </user>
            """)

        # Отправляем ответ на AJAX-запрос
        self.send_response(200)
        self.send_header('Content-type', 'text/plain')
        self.send_header('Access-Control-Allow-Origin', '*')
        self.send_header('Access-Control-Allow-Methods', 'POST, OPTIONS')
        self.send_header('Access-Control-Allow-Headers', 'Content-Type')
        self.end_headers()
        self.wfile.write(bytes('Данные успешно записаны', 'utf-8'))

    def do_OPTIONS(self):
        self.send_response(200)
        self.send_header('Access-Control-Allow-Origin', '*')
        self.send_header('Access-Control-Allow-Methods', 'POST, OPTIONS')
        self.send_header('Access-Control-Allow-Headers', 'Content-Type')
        self.end_headers()

    def handle_login(self):
        content_length = int(self.headers['Content-Length'])
        body = self.rfile.read(content_length).decode('utf-8')
        data = json.loads(body)
        email = data['email']
        password = data['password']

        # Чтение XML-файла
        tree = ET.parse('registrations.xml')
        root = tree.getroot()

        # Поиск пользователя по email
        user_found = False
        for user in root.findall('user'):
            if user.find('email').text == email:
                if user.find('password').text == password:
                    user_found = True
                    self.send_response(200)
                    self.send_header('Content-type', 'text/plain')
                    self.send_header('Access-Control-Allow-Origin', '*')
                    self.send_header('Access-Control-Allow-Methods', 'POST, OPTIONS')
                    self.send_header('Access-Control-Allow-Headers', 'Content-Type')
                    self.end_headers()
                    self.wfile.write(bytes('Вы успешно авторизованы!', 'utf-8'))
                    break
                else:
                    self.send_response(401)
                    self.send_header('Content-type', 'text/plain')
                    self.send_header('Access-Control-Allow-Origin', '*')
                    self.send_header('Access-Control-Allow-Methods', 'POST, OPTIONS')
                    self.send_header('Access-Control-Allow-Headers', 'Content-Type')
                    self.end_headers()
                    self.wfile.write(bytes('Неверный пароль', 'utf-8'))
                    break

        if not user_found:
            self.send_response(404)
            self.send_header('Content-type', 'text/plain')
            self.send_header('Access-Control-Allow-Origin', '*')
            self.send_header('Access-Control-Allow-Methods', 'POST, OPTIONS')
            self.send_header('Access-Control-Allow-Headers', 'Content-Type')
            self.end_headers()
            self.wfile.write(bytes('Пользователь не существует', 'utf-8'))

    def do_OPTIONS(self):
        self.send_response(200)
        self.send_header('Access-Control-Allow-Origin', '*')
        self.send_header('Access-Control-Allow-Methods', 'POST, OPTIONS')
        self.send_header('Access-Control-Allow-Headers', 'Content-Type')
        self.end_headers()

    def handle_get_user(self):
        content_length = int(self.headers['Content-Length'])
        body = self.rfile.read(content_length).decode('utf-8')
        data = json.loads(body)
        email = data['email']

        tree = ET.parse('registrations.xml')
        root = tree.getroot()
        user_found = False
        for user in root.findall('user'):
            if user.find('email').text == email:
                user_found = True
                user_data = {
                    'name': user.find('name').text,
                    'surname': user.find('surname').text,
                    'patronymic': user.find('patronymic').text,
                    'phone': user.find('phone').text,
                    'email': user.find('email').text,
                    'code': user.find('code').text,
                    'password': user.find('password').text
                }
                self.send_response(200)
                self.send_header('Content-type', 'application/json')
                self.send_header('Access-Control-Allow-Origin', '*')
                self.send_header('Access-Control-Allow-Methods', 'POST, OPTIONS')
                self.send_header('Access-Control-Allow-Headers', 'Content-Type')
                self.end_headers()
                self.wfile.write(bytes(json.dumps(user_data), 'utf-8'))
                break
        if not user_found:
            self.send_response(401)
            self.send_header('Content-type', 'text/plain')
            self.send_header('Access-Control-Allow-Origin', '*')
            self.send_header('Access-Control-Allow-Methods', 'POST, OPTIONS')
            self.send_header('Access-Control-Allow-Headers', 'Content-Type')
            self.end_headers()
            self.wfile.write(bytes('Пользователь не найден', 'utf-8'))

    def handle_update_user(self):
        content_length = int(self.headers['Content-Length'])
        body = self.rfile.read(content_length).decode('utf-8')
        data = json.loads(body)
        name = data['name']
        surname = data['surname']
        patronymic = data['patronymic']
        phone = data['phone']
        email = data['email']
        password = data['password']

        tree = ET.parse('registrations.xml')
        root = tree.getroot()
        user_found = False
        for user in root.findall('user'):
            if user.find('email').text == email:
                user_found = True
                user.find('name').text = name
                user.find('surname').text = surname
                user.find('patronymic').text = patronymic
                user.find('phone').text = phone
                user.find('email').text = email
                user.find('password').text = password
                tree.write('registrations.xml', encoding='utf-8', xml_declaration=True)
                self.send_response(200)
                self.send_header('Content-type', 'text/plain')
                self.send_header('Access-Control-Allow-Origin', '*')
                self.send_header('Access-Control-Allow-Methods', 'POST, OPTIONS')
                self.send_header('Access-Control-Allow-Headers', 'Content-Type')
                self.end_headers()
                self.wfile.write(bytes('Данные успешно обновлены!', 'utf-8'))
                break
        if not user_found:
            self.send_response(401)
            self.send_header('Content-type', 'text/plain')
            self.send_header('Access-Control-Allow-Origin', '*')
            self.send_header('Access-Control-Allow-Methods', 'POST, OPTIONS')
            self.send_header('Access-Control-Allow-Headers', 'Content-Type')
            self.end_headers()
            self.wfile.write(bytes('Пользователь не найден', 'utf-8'))


if __name__ == '__main__':
    server = HTTPServer((HOST_NAME, PORT_NUMBER), MyHandler)
    print(f'Сервер запущен на http://{HOST_NAME}:{PORT_NUMBER}')
    try:
        server.serve_forever()
    except KeyboardInterrupt:
        server.server_close()
        print('Сервер остановлен')
