from __future__ import absolute_import
import os.path as op

import numpy as nm

from sfepy import data_dir

from sfepy.base.testing import TestCommon
import six

def init_vec(variables):
    return nm.random.rand(variables.di.ptr[-1])

def check_vec(self, vec, ii, ok, conds, variables):
    from sfepy.discrete.common.dof_info import expand_nodes_to_equations

    for var_name, var_conds in six.iteritems(conds.group_by_variables()):
        var = variables[var_name]
        for cond in var_conds:
            cond.canonize_dof_names(var.dofs)
            self.report('%d: %s %s: %s %s'
                        % (ii, var.name,
                           cond.name, cond.region.name, cond.dofs[0]))
            nods = var.field.get_dofs_in_region(cond.region)
            eq = expand_nodes_to_equations(nods, cond.dofs[0], var.dofs)

            off = variables.di.indx[var_name].start
            n_nod = len(nods)
            for cdof, dof_name in enumerate(cond.dofs[0]):
                idof = var.dofs.index(dof_name)
                eqs = eq[n_nod * cdof : n_nod * (cdof + 1)]

                _ok = nm.allclose(vec[off + eqs], idof,
                                  atol=1e-14, rtol=0.0)
                if not _ok:
                    self.report(' %s: failed! (all of %s == %f)'
                                % (dof_name, vec[off + eqs], idof))
                ok = ok and _ok

    return ok

class Test(TestCommon):

    @staticmethod
    def from_conf(conf, options):
        from sfepy.discrete import FieldVariable, Variables, Problem
        from sfepy.discrete.fem import Mesh, FEDomain, Field

        mesh = Mesh.from_file(data_dir + '/meshes/2d/square_unit_tri.mesh')
        domain = FEDomain('domain', mesh)

        omega = domain.create_region('Omega', 'all')
        domain.create_region('Left',
                             'vertices in (x < -0.499)',
                             'facet')
        domain.create_region('LeftStrip',
                             'vertices in (x < -0.499)'
                             ' & (y > -0.199) & (y < 0.199)',
                             'facet')
        domain.create_region('LeftFix',
                             'r.Left -v r.LeftStrip',
                             'facet')
        domain.create_region('Right',
                             'vertices in (x > 0.499)',
                             'facet')
        domain.create_region('RightStrip',
                             'vertices in (x > 0.499)'
                             ' & (y > -0.199) & (y < 0.199)',
                             'facet')
        domain.create_region('RightFix',
                             'r.Right -v r.RightStrip',
                             'facet')

        fu = Field.from_args('fu', nm.float64, 'vector', omega, approx_order=2)
        u = 
FieldVariable('u', 'unknown', fu)