"""Общие операции новых учебных опытов; встроенный MicroPython FEMM 5.
Файл выполняется через exec в пространстве нативных mi_/mo_/hi_/ho_.
Все координаты магнитных геометрий — миллиметры, результаты — СИ.
"""

import math
import os
import json

MU0 = 4e-7 * math.pi


def result_folder(name):
    # Нельзя незаметно затереть предыдущую серию.
    folder = os.path.abspath(name)
    os.mkdir(folder)
    return folder


def save_json(folder, data):
    with open(os.path.join(folder, "results.json"), "w") as stream:
        json.dump(data, stream)


def pair(value):
    return [value.real, value.imag]


def material(name, mu=1, sigma=0, hc=0, wire_type=0, strands=0, diameter=0):
    mi_addmaterial(
        name, mu, mu, hc, 0, sigma, 0, 0, 1, wire_type, 0, 0, strands, diameter
    )


def label(x, y, name, mesh, circuit="<None>", turns=0, group=0, angle=0):
    mi_addblocklabel(x, y)
    mi_selectlabel(x, y)
    mi_setblockprop(name, 0, mesh, circuit, angle, group, turns)
    mi_clearselected()


def circle(x, y, radius, degree=2):
    mi_addnode(x - radius, y)
    mi_addnode(x + radius, y)
    mi_addarc(x - radius, y, x + radius, y, 180, degree)
    mi_addarc(x + radius, y, x - radius, y, 180, degree)


def half_disk(radius, z=0, degree=2):
    mi_addnode(0, z - radius)
    mi_addnode(0, z + radius)
    mi_addsegment(0, z - radius, 0, z + radius)
    mi_addarc(0, z - radius, 0, z + radius, 180, degree)


def a0_circle(radius, axi=False):
    mi_addboundprop("A0", 0, 0, 0, 0, 0, 0, 0, 0, 0)
    if axi:
        half_disk(radius)
        mi_selectarcsegment(radius, 0)
    else:
        circle(0, 0, radius)
        mi_selectarcsegment(0, radius)
        mi_selectarcsegment(0, -radius)
    mi_setarcsegmentprop(2, "A0", 0, 0)
    mi_clearselected()


def solve(folder, stem):
    mi_saveas(os.path.join(folder, stem + ".fem"))
    mi_analyze(1)
    mi_loadsolution()
    mo_smooth("off")


def close_magnetic():
    mo_close()
    mi_close()
